Last active
October 13, 2020 10:20
-
-
Save mkj-is/15ece603186f416c8a288d9a674464f2 to your computer and use it in GitHub Desktop.
Simple Nibable protocol for simple initialization of views from nib
This file contains hidden or 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
// | |
// Nibable.swift | |
// | |
// Created by Matěj Kašpar Jirásek on 12/08/16. | |
// Copyright © 2016 Matěj Kašpar Jirásek. All rights reserved. | |
// | |
import UIKit | |
protocol Nibable { | |
static var nibName: String { get } | |
} | |
extension Nibable where Self: UIView { | |
static var nibName: String { | |
return NSStringFromClass(self).components(separatedBy: ".").last! | |
} | |
static var nib: UINib { | |
return UINib(nibName: Self.nibName, bundle: nil) | |
} | |
init(owner: AnyObject? = nil) { | |
let views = Self.nib.instantiate(withOwner: owner, options: [:]) | |
for view in views { | |
if let view = view as? Self { | |
self = view | |
return | |
} | |
} | |
fatalError("Nib for class \(Self.nibName) could not be loaded!") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This protocol extension allows us to simply initialize your custom views from nib, the only thing you need is that your custom view class conforms to the
Nibable
protocol and the nib must have same name as the custom class. Then you can initialize your view simply for example like this:YourView(owner: self)