Download a view from XIB and display in a storyboard

For a long time I worked with a custom view with xib files.

In this case, I needed to do the following:

  • Create a file xib -file and swift , the two with the same name.
  • Select the view, set its own class to class in swift -file.
  • Keep working, and if necessary, I create a view like this:

     public extension UIView { class func fromXib() -> UIView { return NSBundle.mainBundle().loadNibNamed(self.nameOfClass, owner: nil, options: nil).first as! UIView } 

Well, it works, no problem. But in another project, I started working more with Storyboard. I would like to custom views appear there, despite the fact that they were created in xib -file (I do this, for example, when the view is displayed on several screens).

So, to solve this problem, I took the following steps:

  • Create a file xib -file and swift , the two with the same name.
  • Instead of setting custom class I set the File owner in class swift -file. (So, my view class is not set, UIView default).
  • I will add the following code to the lifecycle methods:

     required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override init(frame: CGRect) { super.init(frame: frame) setup() } func setup() { let v = NSBundle(forClass: self.dynamicType).loadNibNamed(self.nameOfClass, owner: self, options: nil).first as? UIView addSubview(v!) v?.frame = self.bounds } 
  • I note performance as @IBDesignable .

Again, everything is in order, I add the view to the storyboard screen, set its class to my custom class and ta-daa, it displays it in Interface Builder and loads at runtime of my application.

The problem: how do I put it all together? If I use my method fromXib , application crashes: Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSObject 0x7f9ea2d5b240> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key hoursLabel.

It would be very convenient if I had a way to load views in both directions.

Thanks in advance!

+5
source share

All Articles