Last active
June 29, 2016 20:42
-
-
Save iSapozhnik/f2bdbaf53e0c73a5c763eedcd93c46ba to your computer and use it in GitHub Desktop.
UIView loading from Nib
This file contains hidden or 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
// | |
// UIView+Nib.swift | |
// Pods | |
// | |
// Created by Sapozhnik Ivan on 29.06.16. | |
// | |
// | |
import Foundation | |
// http://stackoverflow.com/a/26326006/1320184 | |
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 mainBundle = NSBundle.mainBundle() | |
let bundlePath = NSBundle.mainBundle().pathForResource("LoadingViewController", ofType: "bundle") | |
let oneMoreBundle = NSBundle(path: bundlePath!) | |
let classBundle = NSBundle(forClass: object_getClass(self)) | |
let nibViews = oneMoreBundle!.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 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment