简体   繁体   中英

How to assign value to tableview cell?

I have the following Swift code, which is mostly auto generated once a tableview is added:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell:UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "test")
    return cell.textLabel.text = "test"
}

I get the following compile time error:

Cannot assign a value of type 'String' to a value of type 'String?'

I have tried ! (unwrapping) in the cell.textLabel.text syntax to no effect. Any ideas what I'm doing wrong?

You're supposed to be returning the cell, not text from cellForRowAtIndexPath. You also should be using dequeueReusableCellWithIdentifier to get your cell.

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCellWithIdentifier("test") as UITableViewCell!
    cell.textLabel?.text = "test"
    return cell
}

The textLabel as a part of the UITableViewCell is optional and therefore you need to change your code to this:

cell.textLabel?.text = "test"
return cell

To add on to this you should not be getting your cell using that method, you should use:

let cell = tableView.dequeueReusableCellWithIdentifier("test", forIndexPath: indexPath) as UITableViewCell

So in the end your code should look like this:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("test", forIndexPath: indexPath) as UITableViewCell
    cell.textLabel?.text = "test"
    return cell
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM