-
-
Save shaps80/00ce25a524ea7abbaf85 to your computer and use it in GitHub Desktop.
This is the best way I've found to load a view from a nib in swift.
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
// | |
// UIView+NibLoading.swift | |
// Sam Dods on 29/10/2015. | |
// | |
import UIKit | |
/// Protocol to be extended with implementations | |
protocol UIViewLoading {} | |
/// Extend UIView to declare that it includes nib loading functionality | |
extension UIView : UIViewLoading {} | |
/// Protocol implementation | |
extension UIViewLoading where Self : UIView { | |
/** | |
Creates a new instance of the class on which this method is invoked, | |
instantiated from a nib of the given name. If no nib name is given | |
then a nib with the name of the class is used. | |
- parameter nibNameOrNil: The name of the nib to instantiate from, or | |
nil to indicate the nib with the name of the class should be used. | |
- returns: A new instance of the class, loaded from a nib. | |
*/ | |
static func loadFromNib(nibNameOrNil: String? = nil) -> Self { | |
let nibName = nibNameOrNil ?? self.className | |
let nib = UINib(nibName: nibName, bundle: nil) | |
return nib.instantiateWithOwner(self, options: nil).first as! Self | |
} | |
static private var className: String { | |
let className = "\(self)" | |
let components = className.characters.split{$0 == "."}.map ( String.init ) | |
return components.last! | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment