Correct way to load a Nib for a UIView subclass

前端 未结 6 1932
挽巷
挽巷 2020-11-29 18:36

I am aware this question has been asked before but the answers are contradicting and I am confused, so please don\'t flame me.

I want to have a reusable UIView

6条回答
  •  执笔经年
    2020-11-29 18:55

    Answering my own question about 2 or something years later here but...

    It uses a protocol extension so you can do it without any extra code for all classes.

    /*
    
    Prerequisites
    -------------
    - In IB set the view's class to the type hook up any IBOutlets
    - In IB ensure the file's owner is blank
    
    */
    
    public protocol CreatedFromNib {
        static func createFromNib() -> Self?
        static func nibName() -> String?
    }
    
    extension UIView: CreatedFromNib { }
    
    public extension CreatedFromNib where Self: UIView {
    
        public static func createFromNib() -> Self? {
            guard let nibName = nibName() else { return nil }
            guard let view = NSBundle.mainBundle().loadNibNamed(nibName, owner: nil, options: nil).last as? Self else { return nil }
            return view
        }
    
        public static func nibName() -> String? {
            guard let n = NSStringFromClass(Self.self).componentsSeparatedByString(".").last else { return nil }
            return n
        }
    }
    
    // Usage:
    let myView = MyView().createFromNib()
    

提交回复
热议问题