Created
October 30, 2015 12:45
-
-
Save Momachilles/e1e10bc40f9aa3b63912 to your computer and use it in GitHub Desktop.
Load custom UIView from Nib in Swift using generics. Thanks to Logan (http://stackoverflow.com/users/2611971/logan)
This file contains 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
class func fromNib<T : UIView>(nibNameOrNil: String? = nil) -> 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