代码之家  ›  专栏  ›  技术社区  ›  Mick F

为什么UILabel()返回nil?

  •  1
  • Mick F  · 技术社区  · 7 年前

    class MyViewCell: UICollectionViewCell {
        @IBOutlet weak var title: UILabel!
    
        override init(frame: CGRect) {
            super.init(frame: frame)
            didLoad()
        }
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            didLoad()
        }
    
        /// Common init code.
        func didLoad() {
            self.title = UILabel()
            self.title.textColor = .white
            ...
        }
    }
    

    我的应用程序在崩溃 self.title.textColor = .white

    fatal error: unexpectedly found nil while unwrapping an Optional value
    

    知道UILabel()返回的原因吗 nil ?

    2 回复  |  直到 7 年前
        1
  •  3
  •   jrturton    7 年前

    您直接将某些内容分配给弱引用,此时没有强拥有引用,因此弱引用立即被删除。当你在下一条线上访问它时,你的得分是零 ! ,这会导致崩溃。

    func didLoad() {
        let label = UILabel()
        // Configure the label...
        self.view.addSubview(label)
        // A view retains its subviews, so now you can assign to the weak reference
        self.title = label
    
    }
    

        2
  •  -1
  •   dhin    7 年前

    确保您的IBOutlet已连接到故事板/xib上

     self.title = UILabel()