Last active
February 17, 2021 07:03
-
-
Save bizz84/ee96cc4750dfab44e2ddf99f81202fa2 to your computer and use it in GitHub Desktop.
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
/* | |
* 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