Skip to content

Instantly share code, notes, and snippets.

@shaps80
Forked from samdods/UIView+NibLoading.swift
Created January 5, 2016 13:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shaps80/00ce25a524ea7abbaf85 to your computer and use it in GitHub Desktop.
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.
//
// 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