I recently started programming using swift(swift newbie! :b)
got an error and have no idea how to fix it :c
this is the code of viewcontroller.swift !
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITableViewDataSource,UITableViewDelegate {
#IBOutlet weak var picker1: UIPickerView!
#IBOutlet weak var keySelect: UITableView!
var Array = ["2", "3", "4"]
#IBOutlet weak var picker1label: UILabel!
#IBOutlet weak var keyselectView: UILabel!
#IBOutlet weak var keylabel: UIButton!
let intervalCellIdentifier = "intervalCellIdentifier"
var intervalNames = ["Q", "W", "E", "R", "T", "Y"]
let limit = 5
var answer1 = 0
override func viewDidLoad() {
super.viewDidLoad()
picker1.delegate = self
picker1.dataSource = self
//edited
keySelect.delegate = self
keySelect.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return Array[row]
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return Array.count
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
#IBAction func submit1(sender: AnyObject) {
if(answer1 == 0) {
picker1label.text = "2"
}
else if(answer1 == 1) {
picker1label.text = "3"
}
else {
picker1label.text = "4"
}
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
answer1 = row
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return intervalNames.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(intervalCellIdentifier,forIndexPath: indexPath) as UITableViewCell
cell.accessoryType = .None
cell.textLabel?.text = intervalNames[indexPath.row]
return cell
}
//MARK: - UITableViewDelegate
func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
if let sr = tableView.indexPathsForSelectedRows {
if sr.count == limit {
let alertController = UIAlertController(title: "Oops", message:
"You are limited to \(limit) selections", preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: {action in
}))
self.presentViewController(alertController, animated: true, completion: nil)
return nil
}
}
return indexPath
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("selected \(intervalNames[indexPath.row])")
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
if cell.selected {
cell.accessoryType = .Checkmark
}
}
if let sr = tableView.indexPathsForSelectedRows {
print("didDeselectRowAtIndexPath selected rows:\(sr)")
}
}
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
print("deselected \(intervalNames[indexPath.row])")
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
cell.accessoryType = .None
}
if let sr = tableView.indexPathsForSelectedRows {
print("didDeselectRowAtIndexPath selected rows:\(sr)")
}
}
}
2016-07-28 23:08:29.868 customkeyboard[60865:1611607] * Assertion failure in -[UITableView dequeueReusableCellWithIdentifier:forIndexPath:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3512.29.5/UITableView.m:6547
2016-07-28 23:08:29.945 customkeyboard[60865:1611607] * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'unable to dequeue a cell with identifier intervalCellIdentifier - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'
this is error explanation(?)
help me :3
1. With XIB file
You have to register the cell to table first, may be in viewDidLoad, as:
let nib = UINib(nibName: "CustomCell", bundle: NSBundle.mainBundle())
tableView.registerNib(nib, forCellReuseIdentifier: "CustomCellIdentifier")
This is applicable if we are using a custom cell with .xib file.
2. Without XIB file
And here is a solution if we are not creating separate .xib file for custom cell:
We need to create dynamic prototype for cell in table view as:
Then we need to provide class name and reuse identifier for our custom cell as:
Here, no need to register class or nib!
Here is the cellForRowAtIndexPath implementation:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Configure the cell...
let cell = tableView.dequeueReusableCellWithIdentifier("CustomTableViewCellId", forIndexPath: indexPath) as! CustomTableViewCell
cell.setCellIndexLabel(indexPath.row)
return cell
}
This implementation will be same for both the above solutions.
3. Only Class Implementation
Without XIB, without Dynamic Prototype
Here is the custom cell without any XIB or Dynamic Prototype:
class WithoutNibCustomTableViewCell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
//do custom initialisation here, if any
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
class func identifier() -> String {
return "WithoutNibCustomTableViewCellId"
}
//MARK: Public Methods
func setCellIndexLabel(index: Int) {
let customLbl = UILabel(frame: CGRectMake(0, 0, 100, 40))
customLbl.text = String(index)
contentView.addSubview(customLbl)
}
}
Then, in table view, we need to register cell class as:
tableView!.registerClass(WithoutNibCustomTableViewCell.classForCoder(), forCellReuseIdentifier: WithoutNibCustomTableViewCell.identifier())
cellForRowAtIndexPath also same as above, like:
let cell = tableView.dequeueReusableCellWithIdentifier(WithoutNibCustomTableViewCell.identifier(), forIndexPath: indexPath) as! WithoutNibCustomTableViewCell
cell.setCellIndexLabel(indexPath.row)
return cell
in cellForRow change this :
let cell = tableView.dequeueReusableCellWithIdentifier(intervalCellIdentifier,forIndexPath: indexPath) as UITableViewCell by
let cell = tableView.dequeueReusableCellWithIdentifier(intervalCellIdentifier,forIndexPath: indexPath) as your cell class name .
I published a pod that will make your life easier while working with cells:
https://cocoapods.org/pods/CellRegistration
It simplifies the API to just one-line:
let : MyCustomCell = tableView.dequeueReusableCell(forIndexPath: indexPath)
Related
I have a textField, which when touch displays a tableView with some rows.
I'm trying to do this: when a user selects one of the rows, the value of row is placed in the textField and the tableView is closed.
The first part works well for me. The user touch on one row and the textField shows the value of that row. But if I want to close the tableview, I have to press twice on the row.
This is my code:
class Redactar_mensaje: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {
var values = ["123 Main Street", "789 King Street", "456 Queen Street", "99 Apple Street", "red", "orange", "yellow", "green", "blue", "purple", "owaldo", "ostras", "Apple", "Pineapple", "Orange", "Adidas"]
#IBOutlet weak var campo_para: UITextField!
#IBOutlet weak var tableView: UITableView!
var originalCountriesList:[String] = Array()
override func viewDidLoad() {
super.viewDidLoad()
tableView.isHidden = true
for country in values {
originalCountriesList.append(country)
}
campo_para.delegate = self
tableView.delegate = self
tableView.dataSource = self
campo_para.addTarget(self, action: #selector(textFieldActive), for: UIControlEvents.touchDown)
campo_para.addTarget(self, action: #selector(searchRecords(_ :)), for: .editingChanged)
}
#objc func searchRecords(_ textField: UITextField) {
self.values.removeAll()
if textField.text?.count != 0 {
for country in originalCountriesList {
if let countryToSearch = textField.text{
let range = country.lowercased().range(of: countryToSearch, options: .caseInsensitive, range: nil, locale: nil)
if range != nil {
self.values.append(country)
}
}
}
} else {
for country in originalCountriesList {
values.append(country)
}
}
tableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return values.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "cellx")
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "cellx")
}
cell?.textLabel?.text = values[indexPath.row]
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
campo_para.text = values[indexPath.row]
tableView.isHidden = true //I need press twice for this. I want press only one
}
func textFieldActive() {
tableView.isHidden = false
}
}
Ideally, the user touches the textField, displays the tableView, chooses one of the values, and it close automatically the tableView. But this last one does not work well.
Any advice?
Details
xCode 8.3, Swift 3.1
Example to Detect Double tap and Single tap on TableViewCell
ViewController.swift
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.tableFooterView = UIView()
}
}
extension ViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell") as! TableViewCell
cell.label.text = "\(indexPath)"
cell.delegate = self
return cell
}
}
extension ViewController:TableViewCellDelegate {
func tableViewCell(singleTapActionDelegatedFrom cell: TableViewCell) {
let indexPath = tableView.indexPath(for: cell)
print("singleTap \(String(describing: indexPath)) ")
}
func tableViewCell(doubleTapActionDelegatedFrom cell: TableViewCell) {
let indexPath = tableView.indexPath(for: cell)
print("doubleTap \(String(describing: indexPath)) ")
//You can hide your textfield here
}
}
TableViewCell.swift
import UIKit
class TableViewCell: UITableViewCell {
#IBOutlet weak var label: UILabel!
private var tapCounter = 0
var delegate: TableViewCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
let tap = UITapGestureRecognizer(target: self, action: #selector(tapAction))
addGestureRecognizer(tap)
}
func tapAction() {
if tapCounter == 0 {
DispatchQueue.global(qos: .background).async {
usleep(250000)
if self.tapCounter > 1 {
self.doubleTapAction()
} else {
self.singleTapAction()
}
self.tapCounter = 0
}
}
tapCounter += 1
}
func singleTapAction() {
delegate?.tableViewCell(singleTapActionDelegatedFrom: self)
}
func doubleTapAction() {
delegate?.tableViewCell(doubleTapActionDelegatedFrom: self)
}
}
TableViewCellDelegate.swift
import UIKit
protocol TableViewCellDelegate {
func tableViewCell(singleTapActionDelegatedFrom cell: TableViewCell)
func tableViewCell(doubleTapActionDelegatedFrom cell: TableViewCell)
}
Result
Here I put my solution, in case someone else would happen something similar.
Just change the order of the lines and add one more line. First it makes it invisible and then puts the result in the textField and, magically, it worked!
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.isHidden = true
campo_para.text = NombreUsuario[indexPath.row]
campo_asunto.becomeFirstResponder()
}
Thanks!
I am unable to trigger an action as i click on the table cell. The background of the pressed cell is just gray after pressing the cell. But the action is not performing. Please help.
import UIKit
class ViewController: UIViewController, UITableViewDataSource , UITableViewDelegate
{
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
var loki_images:[UIImage] = [UIImage(named: "images.png")!,
UIImage(named: "images (1).png")!,
UIImage(named: "images (2).png")!]
var persons = [ "Lokesh Ahuja" , "Raghav Mittal" , "Tul-Tul" ]
var identities = ["A","B","C"]
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return persons.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("Cell")
let Name = persons[indexPath.item]
cell!.textLabel!.text = Name
let image = loki_images[indexPath.row]
cell!.imageView?.image = image
return cell!
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
let id = identities[indexPath.item]
let viewController = storyboard?.instantiateViewControllerWithIdentifier(id)
self.navigationController?.pushViewController(viewController!, animated: true)
}
}
Are your UIViewController is in navigation controller
if not then you should replace
self.navigationController?.pushViewController(viewController!, animated: true)
with
self.present(viewController, animated: true, completion: nil)
Have your proparly connected Table's UITableViewDelegate with View Controller in Storyboard. Check it. If you not connect it than didselect will not called.
im learning swift and i am trying to build an app for logging workouts.
I'm using diefferent views and prototype cells and it works perfect.
But now on one view i have two tableviews, with each of them has the same kind of prototype cell, which is also a custom cell:
import UIKit
class muscleCell: UITableViewCell {
#IBOutlet weak var lblDescription: UILabel!
var id : Int64?
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
It has just an ID and a label. I have used it in another tableview and it works perfect.
I have found here on stackoverflow how to use multiple UITableViews in one View and it showed me the data perfectly with the standard cell.
But as soon as i add the identifier in the storyboard, and make the outlet connections and use these identifiers in the code i get an error.
a quick info, i have tried this line:
self.lvMainMuscles.register(UITableViewCell.self, forCellReuseIdentifier: "mainMuscleCell")
also like this (cause i found it somehwere that it might help):
self.lvMainMuscles.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
but did also not work.
import UIKit
class MachineController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var txtName: UITextField!
#IBOutlet weak var txtType: UITextField!
#IBOutlet weak var deleteToolbar: UIToolbar!
#IBOutlet weak var btnDelete: UIBarButtonItem!
#IBOutlet weak var lvMainMuscles: UITableView!
#IBOutlet weak var lvSupportingMuscles: UITableView!
var machineId: Int64?
var objMachine = Machine(connection: wpdb().db!)
var objMuscle = Muscle(connection: wpdb().db!)
var mainMuscleData : Array<Muscle.structMuscleList> = []
var supportingMuscleData : Array<Muscle.structMuscleList> = []
override func viewDidLoad() {
super.viewDidLoad()
if (machineId != nil) {
if (objMachine.loadById(Id: machineId!) == true) {
self.title = objMachine.name
txtName.text = objMachine.name
txtType.text = String(objMachine.typeId)
}
} else {
deleteToolbar.isHidden = true
}
lvMainMuscles.delegate = self
lvMainMuscles.dataSource = self
lvMainMuscles.allowsMultipleSelection = true
self.lvMainMuscles.register(UITableViewCell.self, forCellReuseIdentifier: "mainMuscleCell")
lvSupportingMuscles.delegate = self
lvSupportingMuscles.dataSource = self
lvSupportingMuscles.allowsMultipleSelection = true
self.lvSupportingMuscles.register(UITableViewCell.self, forCellReuseIdentifier: "supportingMuscleCell")
getData()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func btnSaveClick(_ sender: Any) {
objMachine.name = txtName.text!
objMachine.isSystem = false
objMachine.typeId = Int64(txtType.text!)!
let returnId = objMachine.save()
print("edited/saved id: \(returnId)")
let selectedrows = lvMainMuscles.indexPathsForSelectedRows
if (selectedrows?.count)! > 0 {
for row in selectedrows! {
print(row.row)
}
}
_ = self.navigationController?.popViewController(animated: true)
}
#IBAction func btnDeleteClick(_ sender: Any) {
let alert = UIAlertController(title: title, message: "Do you really want to delete the machine?", preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "Delete", style: .default, handler: { action in
if self.objMachine.delete() == true {
_ = self.navigationController?.popViewController(animated: true)
}
})
let cancelAction = UIAlertAction(title: "Cancel", style: .destructive, handler: nil)
alert.addAction(cancelAction)
alert.addAction(okAction)
self.present(alert, animated: true, completion: nil)
}
func getData() {
mainMuscleData = objMuscle.getList()
supportingMuscleData = objMuscle.getList()
// searchTextField.addTarget(self, action: "textFieldDidChange:", forControlEvents: UIControlEvents.EditingChanged)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.lvMainMuscles {
return mainMuscleData.count
} else {
return supportingMuscleData.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell:muscleCell!
if tableView == self.lvMainMuscles {
cell = tableView.dequeueReusableCell(withIdentifier: "mainMuscleCell") as! muscleCell
cell.lblDescription.text = mainMuscleData[indexPath.row].description
}
if tableView == self.lvSupportingMuscles {
cell = tableView.dequeueReusableCell(withIdentifier: "supportingMuscleCell") as! muscleCell
cell.lblDescription.text = supportingMuscleData[indexPath.row].description
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// tableView.deselectRow(at: indexPath as IndexPath, animated: true)
if tableView == lvMainMuscles {
let cell = self.lvMainMuscles.cellForRow(at: indexPath)!
cell.accessoryType = UITableViewCellAccessoryType.checkmark;
} else {
let cell = self.lvSupportingMuscles.cellForRow(at: indexPath)!
cell.accessoryType = UITableViewCellAccessoryType.checkmark;
}
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if tableView == lvMainMuscles {
let cell = self.lvMainMuscles.cellForRow(at: indexPath)!
cell.accessoryType = UITableViewCellAccessoryType.none;
} else {
let cell = self.lvSupportingMuscles.cellForRow(at: indexPath)!
cell.accessoryType = UITableViewCellAccessoryType.none;
}
}
the error I get is:
Could not cast value of type 'UITableViewCell' (0x10a63c778) to
'WorkoutPartner.muscleCell' (0x107b422f0).
in this line:
cell = tableView.dequeueReusableCell(withIdentifier: "supportingMuscleCell") as! muscleCell
I don't understand why, since I am using the same cell in another view and it works.
i hope you have got an idea,
thank you very much
JYB
From your question and code what I understood is that the two tables have same design for the cells in same UIView.
In this case whenever a cell design is reused, we should make an XIB of your custom table cell, register that NIB with table and then deque in cellForRow
Here is a quick Sample I made for you.
Here is the controller code part:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var firstTable: UITableView!
#IBOutlet weak var secondTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
firstTable.dataSource = self
firstTable.delegate = self
secondTable.dataSource = self
secondTable.delegate = self
//Registering Cell with tables
self.firstTable.register(UINib(nibName: "MuscleTableCell", bundle: nil), forCellReuseIdentifier: "MuscleTableCell")
self.secondTable.register(UINib(nibName: "MuscleTableCell", bundle: nil), forCellReuseIdentifier: "MuscleTableCell")
}
}
extension ViewController : UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.firstTable {
return 5
} else {
return 2
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == self.firstTable {
let cell = tableView.dequeueReusableCell(withIdentifier: "MuscleTableCell") as! MuscleTableCell
cell.descriptionLabel.text = "Muscle Table Cell"
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "MuscleTableCell") as! MuscleTableCell
cell.descriptionLabel.text = "Supporting Table Cell"
return cell
}
}
}
The CustomCellClass
import UIKit
class MuscleTableCell: UITableViewCell {
#IBOutlet weak var descriptionLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
The Custom Cell have its nib file too.
And the Output:
You have registered UITableViewCell.self for the UITableView to use, therefore, it is returning that. Try registering your custom cell class instead.
OK if someone has the same problem:
I solved it by removing these two lines of code:
self.lvMainMuscles.register(UITableViewCell.self, forCellReuseIdentifier: "mainMuscleCell")
and
self.lvSupportingMuscles.register(UITableViewCell.self, forCellReuseIdentifier: "supportingMuscleCell")
I think my error was, that I registered the cell although I have a prototype cell in my storyboard.
Hello I'm in trouble with making UITableview. I made cell as nib file and want to display the cell in the UITableView. But nib file doesn't show in the UItableview when I start the app. I don't know how to figure this out. the source is below
import UIKit
class DownLoadPlayViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
#IBOutlet var tableview: UITableView!
#IBOutlet var totalNumSizeInfo:UILabel!
let cellID:String = "DownLoadPlayViewControllerCell"
var downloadedContents: [Dictionary<String,String>] = []
var showContents: Dictionary<String,String> = [:]
override func viewDidLoad() {
super.viewDidLoad()
self.tableview.delegate = self
self.tableview.dataSource = self
self.tableview.registerClass(DownLoadPlayViewControllerCell.classForCoder(), forCellReuseIdentifier: "DownLoadPlayViewControllerCell")
// self.tableview.registerClass(DownLoadPlayViewControllerCell.self, forCellReuseIdentifier: "DownLoadPlayViewControllerCell")
// self.tableview.registerNib(UINib(nibName: "DownLoadPlayViewControllerCell", bundle: nil), forCellReuseIdentifier: "DownLoadPlayViewControllerCell")
downloadedContents = getDownloadInformation()!;
totalNumSizeInfo.text = "초기화 상태"
// let contentInfo : Dictionary<String,String> = self.downloadedContents[0]
// print(contentInfo["contentTitle"])
// print(contentInfo["viewDate"])
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*Podlist에 있는 다운로드 파일정보를 가져온다. */
func getDownloadInformation() -> [Dictionary<String,String>]?{
var returnValue : [Dictionary<String,String>]? =
NSUserDefaults.standardUserDefaults().objectForKey("downloadedContents") as? [Dictionary<String,String>]
if((returnValue?.isEmpty) == true){
returnValue = nil
}
return returnValue
}
// func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// return 1
// }
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return downloadedContents.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
// let cell = tableView.dequeueReusableCellWithIdentifier("DownLoadPlayViewControllerCell", forIndexPath: indexPath) as! DownLoadPlayViewControllerCell
let cell = tableView.dequeueReusableCellWithIdentifier("DownLoadPlayViewControllerCell") as! DownLoadPlayViewControllerCell
let contentInfo : Dictionary<String,String> = self.downloadedContents[indexPath.row]
cell.titleLabel?.text = contentInfo["contentTitle"]
cell.dateLabel?.text = contentInfo["viewDate"]
return cell;
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
let contentInfo : Dictionary<String,String> = self.downloadedContents[indexPath.row]
print(contentInfo["downLoadURL"])
}
//MARK: ButtonClickArea
#IBAction func closeButtonClick(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
You need reloadData for your tableview after run the command downloadedContents = getDownloadInformation()!. Just run tableview.reloadData() like that:
downloadedContents = getDownloadInformation()!;
tableview.reloadData() //---------> add new like here
totalNumSizeInfo.text = "초기화 상태"
Here is how to use a custom created cell.
Note: I am not using StoryBoard and I have created the cell in a nib.
CustoMCell Class Code:
import UIKit
class ActivityTableViewCell: UITableViewCell {
// MARK: - Constants & variable
// your outlets if any
// MARK: - UITableViewCell methods
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
// MARK: - helper methods
class func cellForTableView(tableView: UITableView, atIndexPath indexPath: NSIndexPath) -> ActivityTableViewCell {
let kActivityTableViewCellIdentifier = "kActivityTableViewCellIdentifier"
tableView.registerNib(UINib(nibName: "ActivityTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: kActivityTableViewCellIdentifier)
let cell = tableView.dequeueReusableCellWithIdentifier(kActivityTableViewCellIdentifier, forIndexPath: indexPath) as! ActivityTableViewCell
return cell
}
}
And this is how I use it in my TableView
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = ActivityTableViewCell.cellForTableView(tableView, atIndexPath: indexPath)
// access your cell properties here
return cell
}
I solve the problem by modifying the tablecellController like this
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.alpha = 0
UIView.animateWithDuration(0.2, delay: 0, options: .CurveEaseIn, animations: {
self.alpha = 1
}, completion: { finished in
})
}
I have a custom cell class with a couple of IBOutlets. I have added the class to the storyboard. I have connected all my outlets. my cellForRowAtIndexPath function looks like this:
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as SwipeableCell
cell.mainTextLabel.text = self.venueService.mainCategoriesArray()[indexPath.row]
return cell
}
Here is my custom cell class:
class SwipeableCell: UITableViewCell {
#IBOutlet var option1: UIButton
#IBOutlet var option2: UIButton
#IBOutlet var topLayerView : UIView
#IBOutlet var mainTextLabel : UILabel
#IBOutlet var categoryIcon : UIImageView
init(style: UITableViewCellStyle, reuseIdentifier: String!) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
}
When I run the app, all my cell are empty. I have logged out self.venueService.mainCategoriesArray() and it contains all the correct strings. I have also tried putting an actual string equal to the label, and that produces the same result.
What am I missing? Any help is appreciated.
Custom Table View Cell Example
Tested with Xcode 9 (edit also tested on 11 / 12 Beta 2) and Swift 4 (edit: also tested on 5.2)
The asker of the original question has solved their problem. I am adding this answer as a mini self contained example project for others who are trying to do the same thing.
The finished project should look like this:
Create a new project
It can be just a Single View Application.
Add the code
Add a new Swift file to your project. Name it MyCustomCell.swift. This class will hold the outlets for the views that you add to your cell in the storyboard.
import UIKit
class MyCustomCell: UITableViewCell {
#IBOutlet weak var myView: UIView!
#IBOutlet weak var myCellLabel: UILabel!
}
We will connect these outlets later.
Open ViewController.swift and make sure you have the following content:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// These strings will be the data for the table view cells
let animals: [String] = ["Horse", "Cow", "Camel", "Sheep", "Goat"]
// These are the colors of the square views in our table view cells.
// In a real project you might use UIImages.
let colors = [UIColor.blue, UIColor.yellow, UIColor.magenta, UIColor.red, UIColor.brown]
// Don't forget to enter this in IB also
let cellReuseIdentifier = "cell"
#IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
// number of rows in table view
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.animals.count
}
// create a cell for each table view row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:MyCustomCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! MyCustomCell
cell.myView.backgroundColor = self.colors[indexPath.row]
cell.myCellLabel.text = self.animals[indexPath.row]
return cell
}
// method to run when table view cell is tapped
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("You tapped cell number \(indexPath.row).")
}
}
Setup the storyboard
Add a Table View to your view controller and use auto layout to pin it to the four sides of the View Controller. Then drag a Table View Cell onto the Table View. And then drag a View and a Label onto the Prototype cell. (You may need to select the Table View Cell and manually set the Row Height to something taller in the Size inspector so that you have more room to work with.) Use auto layout to fix the View and the Label how you want them arranged within the content view of the Table View Cell. For example, I made my View be 100x100.
Other IB settings
Custom class name and Identifier
Select the Table View Cell and set the custom class to be MyCustomCell (the name of the class in the Swift file we added). Also set the Identifier to be cell (the same string that we used for the cellReuseIdentifier in the code above.
Hook Up the Outlets
Control drag from the Table View in the storyboard to the tableView variable in the ViewController code.
Do the same for the View and the Label in your Prototype cell to the myView and myCellLabel variables in the MyCustomCell class.
Finished
That's it. You should be able to run your project now.
Notes
The colored views that I used here could be replaced with anything. An obvious example would be a UIImageView.
If you are just trying to get a TableView to work, see this even more basic example.
If you need a Table View with variable cell heights, see this example.
This is for who are working custom cell with .xib
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let identifier = "Custom"
var cell: CustomCell! = tableView.dequeueReusableCellWithIdentifier(identifier) as? CustomCel
if cell == nil {
tableView.registerNib(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: identifier)
cell =tableView.dequeueReusableCellWithIdentifier(identifier) as? CustomCell
}return cell}
I have the same problem.
Generally what I did is the same as you.
class dynamicCell: UITableViewCell {
#IBOutlet var testLabel : UILabel
init(style: UITableViewCellStyle, reuseIdentifier: String) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
and in the uitableviewcell method:
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell :dynamicCell = tableView.dequeueReusableCellWithIdentifier("cell") as dynamicCell
cell.testLabel.text = "so sad"
println(cell.testLabel)
return cell;
}
and yeah the tableview shows nothing! But guess what, it actually shows something...because the log I get from the println(cell.testLabel) shows that all the Labels are actually displayed out.
BUT! their Frames is strange, which have something like this:
frame = (0 -21; 42 21);
so it has a (0,-21) as (x,y), so that means the label just appears at somewhere outside the bound of the cell.
so I try to add adjust the frame manually like this:
cell.testLabel.frame = CGRectMake(10, 10, 42, 21)
and sadly, it doesn't work.
---------------update after 10 min -----------------
I DID IT.
so, it seems that the problem comes from the Size Classes.
Click on your .storyboard file and go to the File Inspector Tab
UNCHECK THE Size Classes checkbox
and finally, my "so sad"Label comes out!
Thanks for all the different suggestions, but I finally figured it out. The custom class was set up correctly. All I needed to do, was in the storyboard where I choose the custom class: remove it, and select it again. It doesn't make much sense, but that ended up working for me.
Last Updated Version is with xCode 6.1
class StampInfoTableViewCell: UITableViewCell{
#IBOutlet weak var stampDate: UILabel!
#IBOutlet weak var numberText: UILabel!
override init?(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required init(coder aDecoder: NSCoder) {
//fatalError("init(coder:) has not been implemented")
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
Details
Xcode Version 10.2.1 (10E1001), Swift 5
Solution
import UIKit
// MARK: - IdentifiableCell protocol will generate cell identifier based on the class name
protocol Identifiable: class {}
extension Identifiable { static var identifier: String { return "\(self)"} }
// MARK: - Functions which will use a cell class (conforming Identifiable protocol) to `dequeueReusableCell`
extension UITableView {
typealias IdentifiableCell = UITableViewCell & Identifiable
func register<T: IdentifiableCell>(class: T.Type) { register(T.self, forCellReuseIdentifier: T.identifier) }
func register(classes: [Identifiable.Type]) { classes.forEach { register($0.self, forCellReuseIdentifier: $0.identifier) } }
func dequeueReusableCell<T: IdentifiableCell>(aClass: T.Type, initital closure: ((T) -> Void)?) -> UITableViewCell {
guard let cell = dequeueReusableCell(withIdentifier: T.identifier) as? T else { return UITableViewCell() }
closure?(cell)
return cell
}
func dequeueReusableCell<T: IdentifiableCell>(aClass: T.Type, for indexPath: IndexPath, initital closure: ((T) -> Void)?) -> UITableViewCell {
guard let cell = dequeueReusableCell(withIdentifier: T.identifier, for: indexPath) as? T else { return UITableViewCell() }
closure?(cell)
return cell
}
}
extension Array where Element == UITableViewCell.Type {
var onlyIdentifiables: [Identifiable.Type] { return compactMap { $0 as? Identifiable.Type } }
}
Usage
// Define cells classes
class TableViewCell1: UITableViewCell, Identifiable { /*....*/ }
class TableViewCell2: TableViewCell1 { /*....*/ }
// .....
// Register cells
tableView.register(classes: [TableViewCell1.self, TableViewCell2.self]. onlyIdentifiables)
// Create/Reuse cells
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if (indexPath.row % 2) == 0 {
return tableView.dequeueReusableCell(aClass: TableViewCell1.self, for: indexPath) { cell in
// ....
}
} else {
return tableView.dequeueReusableCell(aClass: TableViewCell2.self, for: indexPath) { cell in
// ...
}
}
}
Full Sample
Do not forget to add the solution code here
import UIKit
class ViewController: UIViewController {
private weak var tableView: UITableView?
override func viewDidLoad() {
super.viewDidLoad()
setupTableView()
}
}
// MARK: - Setup(init) subviews
extension ViewController {
private func setupTableView() {
let tableView = UITableView()
view.addSubview(tableView)
self.tableView = tableView
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
tableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
tableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
tableView.register(classes: [TableViewCell1.self, TableViewCell2.self, TableViewCell3.self].onlyIdentifiables)
tableView.dataSource = self
}
}
// MARK: - UITableViewDataSource
extension ViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int { return 1 }
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 20 }
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch (indexPath.row % 3) {
case 0:
return tableView.dequeueReusableCell(aClass: TableViewCell1.self, for: indexPath) { cell in
cell.textLabel?.text = "\(cell.classForCoder)"
}
case 1:
return tableView.dequeueReusableCell(aClass: TableViewCell2.self, for: indexPath) { cell in
cell.textLabel?.text = "\(cell.classForCoder)"
}
default:
return tableView.dequeueReusableCell(aClass: TableViewCell3.self, for: indexPath) { cell in
cell.textLabel?.text = "\(cell.classForCoder)"
}
}
}
}
Results
Uncheck "Size Classes" checkbox works for me as well, but you could also add the missing constraints in the interface builder. Just use the built-in function if you don't want to add the constraints on your own. Using constraints is - in my opinion - the better way because the layout is independent from the device (iPhone or iPad).
It is Purely swift notation an working for me
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cellIdentifier:String = "CustomFields"
var cell:CustomCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? CustomCell
if (cell == nil)
{
var nib:Array = NSBundle.mainBundle().loadNibNamed("CustomCell", owner: self, options: nil)
cell = nib[0] as? CustomCell
}
return cell!
}
[1] First Design your tableview cell in StoryBoard.
[2] Put below table view delegate method
//MARK: - Tableview Delegate Methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return <“Your Array”>
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
var totalHeight : CGFloat = <cell name>.<label name>.frame.origin.y
totalHeight += UpdateRowHeight(<cell name>.<label name>, textToAdd: <your array>[indexPath.row])
return totalHeight
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell : <cell name>! = tableView.dequeueReusableCellWithIdentifier(“<cell identifier>”, forIndexPath: indexPath) as! CCell_VideoCall
if(cell == nil)
{
cell = NSBundle.mainBundle().loadNibNamed("<cell identifier>", owner: self, options: nil)[0] as! <cell name>;
}
<cell name>.<label name>.text = <your array>[indexPath.row] as? String
return cell as <cell name>
}
//MARK: - Custom Methods
func UpdateRowHeight ( ViewToAdd : UILabel , textToAdd : AnyObject ) -> CGFloat{
var actualHeight : CGFloat = ViewToAdd.frame.size.height
if let strName : String? = (textToAdd as? String)
where !strName!.isEmpty
{
actualHeight = heightForView1(strName!, font: ViewToAdd.font, width: ViewToAdd.frame.size.width, DesignTimeHeight: actualHeight )
}
return actualHeight
}
Set tag for imageview and label in cell
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return self.tableData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("imagedataCell", forIndexPath: indexPath) as! UITableViewCell
let rowData = self.tableData[indexPath.row] as! NSDictionary
let urlString = rowData["artworkUrl60"] as? String
// Create an NSURL instance from the String URL we get from the API
let imgURL = NSURL(string: urlString!)
// Get the formatted price string for display in the subtitle
let formattedPrice = rowData["formattedPrice"] as? String
// Download an NSData representation of the image at the URL
let imgData = NSData(contentsOfURL: imgURL!)
(cell.contentView.viewWithTag(1) as! UIImageView).image = UIImage(data: imgData!)
(cell.contentView.viewWithTag(2) as! UILabel).text = rowData["trackName"] as? String
return cell
}
OR
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "imagedataCell")
if let rowData: NSDictionary = self.tableData[indexPath.row] as? NSDictionary,
urlString = rowData["artworkUrl60"] as? String,
imgURL = NSURL(string: urlString),
formattedPrice = rowData["formattedPrice"] as? String,
imgData = NSData(contentsOfURL: imgURL),
trackName = rowData["trackName"] as? String {
cell.detailTextLabel?.text = formattedPrice
cell.imageView?.image = UIImage(data: imgData)
cell.textLabel?.text = trackName
}
return cell
}
see also TableImage loader from github
The actual Apple reference documentation is quite comprehensive
https://developer.apple.com/library/archive/referencelibrary/GettingStarted/DevelopiOSAppsSwift/CreateATableView.html#//apple_ref/doc/uid/TP40015214-CH8-SW2
Scroll down until you see this part