Skip to content

Instantly share code, notes, and snippets.

@gkye
Created April 8, 2016 14:12
Show Gist options
  • Save gkye/4199f4fe410caffb78911bfef1b938bb to your computer and use it in GitHub Desktop.
Save gkye/4199f4fe410caffb78911bfef1b938bb to your computer and use it in GitHub Desktop.
--http://stackoverflow.com/a/26326006/5222077
public extension UIView {
public class func fromNib(nibNameOrNil: String? = nil) -> Self {
return fromNib(nibNameOrNil, type: self)
}
public class func fromNib<T : UIView>(nibNameOrNil: String? = nil, type: T.Type) -> T {
let v: T? = fromNib(nibNameOrNil, type: T.self)
return v!
}
public class func fromNib<T : UIView>(nibNameOrNil: String? = nil, type: T.Type) -> 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 = nibName
}
let nibViews = NSBundle.mainBundle().loadNibNamed(name, owner: nil, options: nil)
for v in nibViews {
if let tog = v as? T {
view = tog
}
}
return view
}
public class var nibName: String {
let name = "\(self)".componentsSeparatedByString(".").first ?? ""
return name
}
public class var nib: UINib? {
if let _ = NSBundle.mainBundle().pathForResource(nibName, ofType: "nib") {
return UINib(nibName: nibName, bundle: nil)
} else {
return nil
}
}
}
let myCustomView = CustomView.fromNib()
// or if you're unsure whether or not the nib exists
let myCustomView: CustomView? = CustomView.fromNib()
//If you need to be specific about the nib name for whatever reason, pass a string arg:
let myCustomView = MyCustomView.fromNib("non-conventional-name")
//Using this with a private view class seems to cause issues. This appears to be a system wide issue.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment