简体   繁体   English

UITableViewCell插座

[英]UITableViewCell outlets

When do outlets get bound to a UITableViewCell instance? 插座何时绑定到UITableViewCell实例? If I print myLabel in the debugger, it's nil and prints: 如果我在调试器中打印myLabel,它将为nil并打印:

fatal error: unexpectedly found nil while unwrapping an Optional value

class MyTableViewCell: UITableViewCell {
   @IBOutlet var myLabel: UILabel!

 override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
  super.init(style: style, reuseIdentifier: reuseIdentifier)
 }

 required init?(coder aDecoder: NSCoder) {
   super.init(coder: aDecoder)

   print("\(myLabel)")
 }
}

Outlets are not yet set when the init method of your tableview cell is called! 调用表视图单元格的init方法时,尚未设置插座!

I'm not sure what your intention is: 我不确定您的意图是什么:

  1. If you want to make sure you are not unwrapping a nil optional value just use if let like this: 如果要确保您没有解开nil可选值,请使用if let如下所示:

     if let label = myLabel { print("\\(label)") } 
  2. If you want to setup the cell of your tableView, you should first register the cell by calling tableView.registerNib(UINib(nibName: "MyTableViewCell", bundle: nil), forCellReuseIdentifier: "reuse") . 如果要设置tableView的单元格,则应首先通过调用tableView.registerNib(UINib(nibName: "MyTableViewCell", bundle: nil), forCellReuseIdentifier: "reuse")注册该单元格。 Then dequeue the cell in cellForRowAtIndexPath using tableView.dequeueReusableCellWithIdentifier("reuse") and make sure you set the values of your cell in awakeFromNib : 然后使用tableView.dequeueReusableCellWithIdentifier("reuse")使cellForRowAtIndexPath的单元出队,并确保在awakeFromNib设置单元的值:

     override func awakeFromNib() { super.awakeFromNib() //you can be sure that myLabel is initialzed here print("\\(myLabel)") } 

If you are connecting an outlet from the Main Storyboard, your problem could arise if the outlet was accidentally deleted. 如果您要从主故事板上连接插座,则意外删除插座可能会引起问题。 Recreate the outlet and the label will not be nil anymore. 重新创建出口,标签将不再为零。

The issue is that you are running into a case where myLabel is nil. 问题是您遇到myLabel为nil的情况。 It could be while the table view cell is being recycled. 可能是在回收表视图单元格的同时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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