Swift 懶加載


1.常見懶加載方法

class ViewController: UIViewController {
    
    lazy var label: UILabel = {
        let label = UILabel(frame: .zero)
        label.translatesAutoresizingMaskIntoConstraints = false
        label.textColor = .black
        label.font = UIFont.systemFont(ofSize: 16, weight: .bold)
        return label
    }()
}

 

2.懶加載使用weak  還是 unowned?

[weak self]  in

還是用
[unowned self]  in

如果你能保證在使用過程中引用對象不會為nil,用unowned 。如果不能,那么就用weak

 

3.工廠方法 + 懶加載

class ViewController: UIViewController {
    
    lazy var label: UILabel = self.createCustomLabel()

    private func createCustomLabel() -> UILabel {
        print("被調用")
        let label = UILabel(frame: .zero)
        label.translatesAutoresizingMaskIntoConstraints = false
        label.textColor = .black
        label.font = UIFont.systemFont(ofSize: 16, weight: .bold)
        return label
    }
}


 

4.如果希望在多處使用,使用靜態工廠 + 懶加載

class ViewController: UIViewController {
    
    lazy var label: UILabel = UILabel.createCustomLabel()
}

extension UILabel {

    static func createCustomLabel() -> UILabel {
        let label = UILabel(frame: .zero)
        label.translatesAutoresizingMaskIntoConstraints = false
        label.textColor = .black
        label.font = UIFont.systemFont(ofSize: 16, weight: .bold)
        return label
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM