"UITableViewCell? Does not have a member named 'textLabel'
I have searched for an answer to this question but with no success. I am basically following the tutorial on how to create a simple todo app, many others comment on the same error as below. The author has no solution yet. Any help would be greatly appreciated.
I am getting the error: 'UITableViewCell?' does not have a member named 'textLabel'
Here's my code:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// tells iphone what to put in each cell
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
// Tells iphone how many cells ther are
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
cell.textLabel?.text = "table cell content"
return cell!
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
source to share
I am following the same tutorial, so I feel your pain! :) In the tutorial, you have to delete and recreate the view controller, and only then it forgets to mention that you need to call the view controller again. Anyway, to save some degradation, just create a new project, drop the table view into the view controller, right click on the table view and bind the dataSource, delegate and view the View Viewer.
Next, here is the code that works for me with XCode 6.1. God knows what they will change further. But, in short, you don't need a "?" after textLabel.
import UIKit
class ViewController: UIViewController, UITableViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var items = ["test 1", "test 2", "test 3", "test 4"]
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")
cell.textLabel.text = self.items[indexPath.row]
return cell
}
}
Hope it helps.
source to share
I had to wrestle with the same / similar question today. This is because you are trying to use custom cells in a standard table view controller. You have to tell the controller in the function that the cell with its custom name should be used as (= instead of TableViewCell). Then Xcode will know where to look for names.
So, right after closing the curly braces for indexPath, you enter:
as! TableViewCell
source to share