我正在尝试使用Swift语言在Custom Tableview Cell中为UILabel分配文本。但它给出错误说明 "fatal error: Can't unwrap Optional.None"
我的自定义单元格代码如下
import UIKit
class NameTableCell: UITableViewCell {
@IBOutlet var lblName: UILabel?
init(style: UITableViewCellStyle, reuseIdentifier: String!) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
我在VIewController中使用它的方式如下
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
{
var cell:NameTableCell = self.tblNames.dequeueReusableCellWithIdentifier("nameCell", forIndexPath: indexPath) as NameTableCell
cell.lblName!.text="test"
return cell
}
我也按照
中的建议尝试了上述功能https://stackoverflow.com/a/24113844/1030951
但无法成功并获得相同的错误。请帮助我解决问题。
答案 0 :(得分:0)
这是一个清单,以确保您正确使用自定义单元格。
在TableView
中的InterfaceBuilder中创建一个原型单元格。
写入CustomCell
课程后,请使用检查员更改您的课程
将单元格的类格式化为CustomCell
。
将所有@IBOutlet
个装饰添加到该原型单元格并连接它们。
如果要更改重用标识符,请确保标识符 原型单元格与您的代码中使用的单元格匹配。
您的tableView
功能代码应如下所示:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIndentifier("ReuseID", for IndexPath:indexPAth) as CustomCell
cell.customLabel.text = "some text"
return cell
我为代码格式化道歉,似乎存在编辑问题。
答案 1 :(得分:0)
怎么样.....
cell.textLabel.text = "test"
答案 2 :(得分:0)
我认为你需要在viewDidLoad方法中注册nib(如果有任何nib),
var nipName=UINib(nibName: "CustomCell", bundle:nil)
tableView.registerNib(nipName, forCellReuseIdentifier: "CustomCell")
如果您正在使用故事板,那么我认为您需要为同一个
注册课程tableView.registerClass(CustomCell.self, forCellReuseIdentifier: "CustomCell")
和像这样的cellforRowAtIndexPath
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!{
var cell = tableView.dequeueReusableCellWithIdentifier("CustomCell", forIndexPath: indexPath) as CustomCell
cell.lblText.text = allList[indexPath.row]
return cell
}
答案 3 :(得分:0)
最后我的问题解决了,但有一个非常奇怪的解决方案。
My Cell的标识符是“nameCell”,当我将其更改为“NameCell”时,它工作正常。
我认为“nameCell”标识符可能会导致与任何系统关键字冲突。
我试过调试两次,当标识符为“nameCell”时应用程序崩溃,当标识符为“NameCell”时工作正常