Swift Tricks

My own, mostly internal blog of Swift tips and tricks

Loading custom UIView nib files

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()

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