Skip to content

Instantly share code, notes, and snippets.

@bizz84
Last active February 17, 2021 07:03
Show Gist options
  • Save bizz84/ee96cc4750dfab44e2ddf99f81202fa2 to your computer and use it in GitHub Desktop.
Save bizz84/ee96cc4750dfab44e2ddf99f81202fa2 to your computer and use it in GitHub Desktop.
/*
* Protocol, extension and base class to load any UIView from nib in Interface Builder or programmatically.
* Example sage:
* @IBDesignable class MyView: UIViewNibLoadable {
* // IBOutlets, IBActions, other view logic here
* }
*
* let myView = MyView() // will load from MyView.xib and attach all outlets / actions
*/
import UIKit
public protocol NibLoadable {
func loadFromNib()
}
public extension NibLoadable where Self: UIView {
func loadFromNib() {
let bundle = Bundle(for: Self.self)
let nibName = (String(describing: type(of: self)) as NSString).components(separatedBy: ".").last!
guard let view = bundle.loadNibNamed(nibName, owner: self, options: nil)?.first as? UIView else {
print("Could not load nib with name: \(nibName)")
return
}
view.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
view.frame = bounds
self.addSubview(view)
self.translatesAutoresizingMaskIntoConstraints = false
}
}
open class UIViewNibLoadable: UIView, NibLoadable {
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
loadFromNib()
}
public override init(frame: CGRect) {
super.init(frame: frame)
loadFromNib()
awakeFromNib()
}
public convenience init() {
self.init(frame: .zero)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment