Skip to content

Instantly share code, notes, and snippets.

@loganwright
Created October 25, 2015 05:34
Show Gist options
  • Save loganwright/c477ddec9b45fbbd967e to your computer and use it in GitHub Desktop.
Save loganwright/c477ddec9b45fbbd967e to your computer and use it in GitHub Desktop.
UIView+Nibs Swift
extension UIView {
class func fromNib(nibNameOrNil: String? = nil) -> Self {
return fromNib(nibNameOrNil, type: self)
}
class func fromNib<T : UIView>(nibNameOrNil: String? = nil, type: T.Type) -> T {
let v: T? = fromNib(nibNameOrNil)
return v!
}
class func fromNib<T : UIView>(nibNameOrNil: String? = nil) -> T? {
var view: T?
let name: String
if let nibName = nibNameOrNil {
name = nibName
} else {
// Most nibs are demangled by practice, if not, just declare string explicitly
name = "\(T.self)".componentsSeparatedByString(".").last!
}
let nibViews = NSBundle.mainBundle().loadNibNamed(name, owner: nil, options: nil)
for v in nibViews {
if let tog = v as? T {
view = tog
}
}
return view
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment