Last active
June 24, 2021 09:57
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
.swift
file for your custom view and a.xib
file with the same name..swift
file.NibLoadable
for your custom view as below:Now you can load the
CustomView
in your xib/storyboard.