Bundle.instantiateNibWithName("MyNibName") as! MyNib // uhhh, what??
😩 That is what I normally end up writing on the first stab... Clearly that is completely wrong. I wish there was a way to get the .xib to a UIView subclass in a much less complicated way. And THERE IS! 😁
Just have your UIView subclass conform to NibInstantiating and you just have to remember the very intuitive words viewFromNib rather than Bundle(for: TheClass.self).loadNibNamed("UghAString", owner: nil, options: nil).
class TextInputBar: UIView, NibInstantiating {
to instantiate, just call viewFromNib
Isn't that so much nicer on the brain!?
Here's the protocol and extension:
let inputBar = TextInputBar.viewFromNib()
Isn't that so much nicer on the brain!?
Here's the protocol and extension:
protocol NibInstantiating: class {
static var nibName: String { get }
}
extension NibInstantiating {
static func viewFromNib() -> Self! {
var view: Self!
let objects = Bundle(for: self).loadNibNamed(nibName, owner: nil, options: nil)
for object in objects! {
guard let foundView = object as? Self else { continue }
view = foundView
break
}
assert(view != nil, "Could not find object of type: \(Self.self) \(#function)")
return view
}
static var nibName: String { return String(describing: Self.self) }
}
To download the code, click here: NibInstantiating.
No comments:
Post a Comment