Dan Beaulieu Dan Beaulieu - 3 months ago 8
iOS Question

'UITableViewCell?' does not have a member named 'textLabel'

I've searched around for an answer to this one but haven't had any success. I am essentially following a tutorial to create a simple todo app, many other's are commenting with the same error as below. The author doesn't have a solution yet. Any help would be appreciated.

I'm getting the error: 'UITableViewCell?' does not have a member named 'textLabel'

Here's my code so far:

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.
}


}

Answer

I am following the same tutorial, so I can feel your pain! :) In the tutorial the fellow has you delete and recreate the view controller, only then he forgets to mention that you need to name your view controller again. Any way, to save some aggravation, just create a new project, drop a Table View into the view controller, right click on the Table View, and link dataSource, delegate, and view to the View Controller.

Next, here is the code that works for me as of XCode 6.1. God knows what they are going to change next. But in short, you don't need the '?' 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 that helps.