简体   繁体   中英

Getting UITableViewCell Properties From Cell Row

I have been trying to learn the ways of UITableViewControllers and I have been encountering an error. Here is the relevant part of my code:

class celly : UITableViewCell {
var name : String = ""
} 

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    println(String((tableView.cellForRowAtIndexPath(indexPath.row) as! celly).name))
}

Here is the error for the second to last line (the println(...) ). It is not the real error... I think :[)

Cannot find initializer for type 'String' that accepts an argument list of type '(String)' 

Does anybody know why my line is not working?

Thanks a lot in advance. Any help is greatly appreciated!

The error is incorrectly used row . Method tableView:cellForRowAtIndexPath: is accepting a NSIndexPath , so you have to call it with indexPath not with indexPath.row .

println(String((tableView.cellForRowAtIndexPath(indexPath) as! celly).name))

To spot similar errors easily, you might consider destructuring statements into simple and readable ones:

Destructuring:

let cell = tableView.cellForRowAtIndexPath(indexPath) as! celly
let name = cell.name

println(name)

The error message is a bug and I would consider report it.

tableView.cellForRowAtIndexPath(indexPath.row) throws an error. The reason for this is that cellForRowAtIndexPath() takes an argument list of NSIndexPath , not an Int . By using indexPath.row , you're returning an Int rather than the required NSIndexPath . To fix this, simply remove the .row :

println((tableView.cellForRowAtIndexPath(indexPath) as! celly).name)

and you should be able to run it.

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