在Swift中简单的UITableView – 意外地发现了零
很简单的代码:
func numberOfSectionsInTableView(tableView: UITableView?) -> Int { return 1 } func tableView(tableView:UITableView!, numberOfRowsInSection section:Int) -> Int { return 5 } func tableView(tableView:UITableView!, cellForRowAtIndexPath indexPath:NSIndexPath!) -> UITableViewCell! { let cell: BookTableViewCell = BookTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "BookCell") println("ip: \(indexPath.row)") cell.bookLabel.text = "test" return cell }
在cell.bookLabel.text行我得到这个:
fatal error: unexpectedly found nil while unwrapping an Optional value
BookTableViewCell是这样定义的:
class BookTableViewCell: UITableViewCell { @IBOutlet var bookLabel: UILabel override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
而bookLabel正确地连接在Storyboard中的Prototype单元格中。 为什么我得到这个错误?
当您在代码中创build视图时,其IBOutlet
属性不能正确连接。 你想要从dequeueReusableCellWithIdentifier
获得的版本:
let cell = tableView.dequeueReusableCellWithIdentifier("BookCell") as BookTableViewCell
如果您正在使用故事板,请确保在文件开始处没有此行:
self.tableView.registerClass(CustomTableViewCell.self, forCellReuseIdentifier: "customCell")
它将覆盖故事板,因此,故事板中的出口链接将被忽略。
我得到这个错误,因为我没有在自定义单元格的故事板上写的标识符。
还要确保它符合你的代码:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("CustomTableCell") as CustomTableCell ... }
可能你在Main.Storyboard中的视图在ViewController文件中丢失了它的IBOutlet引用,只是再次链接它。
在我的情况下,这是可选的解包方式:
let cellId:String = "ConverterTableCell" let cell: ConverterTableViewCell = (tableView.dequeueReusableCellWithIdentifier(cellId)! as? ConverterTableViewCell)!
不要忘记注册笔尖(用Swift3testing),例如,在重写func viewDidLoad() :
self.tableView.register(UINib(nibName: "BookTableViewCell", bundle: nil), forCellReuseIdentifier: "BookCell")
尝试这样做:
let cell = tableView.dequeueReusableCellWithIdentifier("BookCell", forIndexPath: indexPath) as! BookTableViewCell
不要忘记在故事板中设置重用标识符
我得到这个错误,每当我使用重用Identifer名称不同于自定义类名 unifid这些名字为我解决它
我遇到这个错误,如果我把UITapGestureRecognizer放在一个自定义的故事板上的UITableViewCell(Xcode版本是8.3)。