Swift proper way to load xib file

后端 未结 3 1810
死守一世寂寞
死守一世寂寞 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:30

    This works for me:

    class IconTextField: UITextField {
        @IBOutlet weak var view: UIView!
        @IBOutlet weak var test: UIButton!
    
        required init(coder: NSCoder) {
            super.init(coder: coder)
            NSBundle.mainBundle().loadNibNamed("IconTextField", owner: self, options: nil)
            self.addSubview(view)
            assert(test != nil, "the button is conected just like it's supposed to be")
        }
    }
    

    Once loadNibNamed:owner:options: is called the view and test button are connected to the outlets as expected. Adding the nib's view self's subview hierarchy makes the nib's contents visible.

    0 讨论(0)
  • 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
      }
    
    }
    
    0 讨论(0)
  • 2020-12-10 13:39

    You can use this:

    if let customView = Bundle.main.loadNibNamed("MyCustomView", owner: self, options: nil)?.first as? MyCustomView {
            // Set your view here with instantiated customView
    }
    
    0 讨论(0)
提交回复
热议问题