Skip to content

Instantly share code, notes, and snippets.

@samdods
Last active July 31, 2018 21:07
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save samdods/397fbaa01dfbe746e2a9 to your computer and use it in GitHub Desktop.
Save samdods/397fbaa01dfbe746e2a9 to your computer and use it in GitHub Desktop.
This is the best way I've found to instantiate a view from a nib in Swift.
//
// 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(nil, 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