Swift Tricks

My own, mostly internal blog of Swift tips and tricks

Loading custom UIView nib files

@todo add more info, but when instantiating it from a storyboard/xib:

  1. Create a nib & class file
  2. Set the nib's File Owner to the class, but the class name of the actual view should just be UIView
  3. After this, connect the IBOutlets (they should have file owner pointer, not to class)
  4. Make sure the UIView class subclasses NibView (in RDM project)
  5. Now just add a UIView in other xib or storyboard and set the class to your new custom class

Create a UIView extension

First, we need to add an extension to UIView:

extension UIView {
    public class func loadNib<T: UIView>() -> T {
        return Bundle(for: T.self).loadNibNamed(String(describing: T.self), owner: nil, options: nil)![0] as! T
    }
}

Create a UIView subclass and related nib file

Now create a UIView subclass and a nib file. Make sure to perform the following steps:

  • The class name, the class's filename, and the nib's filename should all be the same (CustomView.swift, CustomView.nib)
  • Set the top level view to CustomView in Interface Builder
  • Set the File's Owner to CustomView

Instantiate and add subview

We are now ready to use the class. Simply instantiate it like so:

// In some view controller...
let customView: CustomView = CustomView.loadNib()
self.view.addSubview(customView)

Make sure to explicitly declare the type, otherwise it will try to create a UIView class and fail.