Created
January 18, 2020 14:36
-
-
Save e-sung/82a777fdab879e87e9d8db49afa4b152 to your computer and use it in GitHub Desktop.
Helper protocol that helps initilizing views with xib. This gist is only valid when `xib file` has same file name with `swift file`
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 XibGenerated { | |
func setUpXib() | |
func setUpViews() | |
} | |
extension XibGenerated where Self: UIView { | |
public func setUpXib(bundle: Bundle? = nil) { | |
let viewType = type(of: self) | |
let bundle = bundle ?? Bundle(for: viewType) | |
let nibName = String(describing: viewType) | |
let nib = UINib(nibName: nibName, bundle: bundle) | |
guard let viewXib = nib.instantiate(withOwner: self, options: nil).first as? UIView else { | |
assertionFailure("Expected to instantiate view from nib named \"\(nibName)\" in bundle \"\(bundle.bundleIdentifier ?? "invalid bundle")") | |
return | |
} | |
viewXib.frame = bounds | |
viewXib.translatesAutoresizingMaskIntoConstraints = false | |
addSubview(viewXib) | |
viewXib.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true | |
viewXib.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true | |
viewXib.topAnchor.constraint(equalTo: topAnchor).isActive = true | |
viewXib.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true | |
} | |
public func setUpViews() {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment