ios - UITableViewCell socket

标签 ios swift uitableview

outlet 什么时候绑定(bind)到 UITableViewCell 实例?如果我在调试器中打印 myLabel,它为 nil 并打印:

fatal error :在展开可选值时意外发现 nil

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)")
 }
}

最佳答案

调用 tableview 单元格的 init 方法时尚未设置 socket !

我不确定你的意图是什么:

  1. 如果你想确保你没有解包一个 nil 可选值,只需像这样使用 if let:

    if let label = myLabel {
       print("\(label)")
    }
    
  2. 如果您想设置 tableView 的单元格,您应该首先通过调用 tableView.registerNib(UINib(nibName: "MyTableViewCell", bundle: nil), forCellReuseIdentifier: "reuse"来注册单元格)。然后使用 tableView.dequeueReusableCellWithIdentifier("reuse") 使 cellForRowAtIndexPath 中的单元格出队,并确保在 awakeFromNib 中设置单元格的值:

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

关于ios - UITableViewCell socket ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36291746/

相关文章:

iOS 7 UITableView : is it a bug or is it me?

ios - 有条件地使用时间戳下载文件,例如curl -z

ios - 当 UNNotificationExtensionUserInteractionEnabled 为真时,如何从 UNNotificationContentExtension 触发 didReceiveRemoteNotification

ios - Swift UIPickerView 第一个组件更改第二个组件数据

ios - 一些不需要的 UIImageViews 在尝试将它们设置为 UITableView 的边框时消失

ios - UIImage 没有出现

ios - 导航和选项卡 View Controller 未正确加载,然后跳转到位

ios - ARC 中过度保留的调试策略?

ios - 使用 MBTiles 在离线 map 中自动将 RMMarker 调整为用户的当前位置

arrays - DetailViewController 没有收到对象数组?