我有以下Swift代码,一旦添加了tableview,它主要是自动生成的:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "test")
return cell.textLabel.text = "test"
}
我收到以下编译时错误:
Cannot assign a value of type 'String' to a value of type 'String?'
我在!
语法中尝试cell.textLabel.text
(解包)无效。我有什么想法我做错了吗?
答案 0 :(得分:2)
您应该返回单元格,而不是来自cellForRowAtIndexPath的文本。您还应该使用dequeueReusableCellWithIdentifier来获取您的单元格。
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("test") as UITableViewCell!
cell.textLabel?.text = "test"
return cell
}
答案 1 :(得分:1)
作为UITableViewCell的一部分的textLabel是可选的,因此您需要将代码更改为:
cell.textLabel?.text = "test"
return cell
要添加到此,您不应该使用该方法获取您的单元格,您应该使用:
let cell = tableView.dequeueReusableCellWithIdentifier("test", forIndexPath: indexPath) as UITableViewCell
所以最后你的代码应该是这样的:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("test", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = "test"
return cell
}