Created
March 20, 2017 18:10
-
-
Save JasonCanCode/dd5845396ca52433ae2eb12e006b2842 to your computer and use it in GitHub Desktop.
Protocol used by a UIView subclass for xibs
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
import UIKit | |
/** | |
The adopting UIView is the File Ower of a nib by the same name. All IBOutlets are wired through the File Owner (not the content view itself) and the content view is also wired to the IBOutlet `view`. | |
NOTE - `loadFromNib:` must be called within a convenience initializer. | |
Keep in mind that any UIView instance method that you would normally use `self` should be called `view` instead. | |
*/ | |
protocol NibViewType: UIAppearance { | |
var view: UIView! { get set } | |
func loadFromNib() | |
} | |
extension NibViewType where Self: UIView { | |
func loadFromNib() { | |
if let identifier = NSStringFromClass(self.classForCoder).components(separatedBy: ".").last { | |
Bundle.main.loadNibNamed(identifier, owner: self, options: nil) | |
view.frame = self.frame | |
addSubview(view) | |
} else { | |
assertionFailure("View could not be loaded from a nib. Make sure that the nib file shares the same name as the view class that is the file's owner and that the content view is mapped to owner's view IBOutlet.") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment