Skip to content

Instantly share code, notes, and snippets.

@congnd
Last active June 24, 2021 09:57
Show Gist options
  • Save congnd/8c3c64eda535d3d3de3e030bb4bc37a3 to your computer and use it in GitHub Desktop.
Save congnd/8c3c64eda535d3d3de3e030bb4bc37a3 to your computer and use it in GitHub Desktop.
A protocol that allows you to load a view from a xib file into another xib or storyboard. https://stackoverflow.com/a/47295926
public protocol NibLoadable {
static var nibName: String { get }
}
public extension NibLoadable where Self: UIView {
public static var nibName: String {
return String(describing: Self.self)
}
public static var nib: UINib {
let bundle = Bundle(for: Self.self)
return UINib(nibName: Self.nibName, bundle: bundle)
}
func setupFromNib() {
guard let view = Self.nib.instantiate(withOwner: self, options: nil).first as? UIView else { fatalError("Error loading \(self) from nib") }
addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
view.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 0).isActive = true
view.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
view.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor, constant: 0).isActive = true
view.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true
}
}
@congnd
Copy link
Author

congnd commented Feb 20, 2019

Usage:

  1. Create a .swift file for your custom view and a .xib file with the same name.
  2. Set the File's owner of the .xib file to the .swift file.
  3. Do what ever you want with the .xib file.
  4. Implement the NibLoadable for your custom view as below:
@IBDesignable
class CustomView: UIView, NibLoadable {
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupFromNib()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupFromNib()
    }
}

Now you can load the CustomView in your xib/storyboard.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment