Reputation: 2612
I am making a to-do app in Swift, and I am trying to display the tasks using a UITableView. Users add a task, and press "Done". The UITableView is brought back to the front, and the app crashes. Here is my code:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: nil) //crashes on this line
cell.textLabel!.text = taskMgr.tasksArray[indexPath.row].name
cell.detailTextLabel!.text = taskMgr.tasksArray[indexPath.row].desc
return cell
}
Funny enough, this line works fine in another very similar app I quickly created. Could anyone please point me in the right direction? I am happy to add more detail if necessary.
Upvotes: 0
Views: 2282
Reputation: 23882
Use reuse identifier
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell:UITableViewCell = self.tblSwift.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
cell.textLabel.text = self.items[indexPath.row]
return cell
}
With Detail Title
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell = tableView.dequeueReusableCellWithIdentifier("cell") as? UITableViewCell
if cell == nil {
cell = UITableViewCell(style: .Subtitle, reuseIdentifier: "cell")
}
cell!.textLabel.text = self.names[indexPath.row]
cell!.detailTextLabel.text = self.emails[indexPath.row]
return cell
}
Upvotes: 0
Reputation: 2568
I wrote like this:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:CustomCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CustomCell
cell.lblText.text = "Testing"
return cell
}
Upvotes: 1
Reputation: 4403
You should refactor your code to take advantage of the performance of a UITableView. Your cells can be re-used instead of re-created each time they are displayed on screen.
To do this, you should remove the init method call of UITableViewCell. Instead replace it with: dequeueReusableCellWithIdentifier:forIndexPath:
New in iOS 6, the pattern is to register a TableViewCell subclass with the tableview with the reuse identifier. Then you can easily grab a re-usable cell with dequeReusableCellWithIdentifier:forindexPath:
In viewDidLoad
or somewhere before the tableview datasource/delegate methods are called, you should make a call to register your cell subclass.
registerClass:forCellReuseIdentifier:
For you, in Swift, you'll want to call:
tableview.registerClass(UITableViewCell.self, identifier:"MyReuseIdentifier")
// note there is also a method to register nibs
Then in the cellForRowAtIndexPath method:
tableView.dequeReusableCellWithIdentifier("MyReuseIdentifier", forIndexPath: indexPath)
Upvotes: 0