Swift proper way to load xib file

后端 未结 3 1817
死守一世寂寞
死守一世寂寞 2020-12-10 13:14

I have some strange problem with loading xib file in swift project. It\'s so frustrating because I already know how to do it in Obj-C. But since swift is swift so you can\'t

3条回答
  •  爱一瞬间的悲伤
    2020-12-10 13:39

    I prefer to load from nib, by implementing loadFromNib() function in a protocol extension as follows:

    (as explained here: https://stackoverflow.com/a/33424509/845027)

    import UIKit
    
    protocol UIViewLoading {}
    extension UIView : UIViewLoading {}
    
    extension UIViewLoading where Self : UIView {
    
      // note that this method returns an instance of type `Self`, rather than UIView
      static func loadFromNib() -> Self {
        let nibName = "\(self)".characters.split{$0 == "."}.map(String.init).last!
        let nib = UINib(nibName: nibName, bundle: nil)
        return nib.instantiateWithOwner(self, options: nil).first as! Self
      }
    
    }
    

提交回复
热议问题