Last active
November 12, 2017 07:59
-
-
Save oney/bfc073d43be4c307efa9f640a076326a to your computer and use it in GitHub Desktop.
based on https://stackoverflow.com/a/42032715
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
extension UIView { | |
public class func fromNib(nibName: String? = nil, owner: Any? = nil) -> Self { | |
return fromNib(nibName: nibName, type: self, owner: owner) | |
} | |
public class func fromNib<T: UIView>(nibName: String? = nil, type: T.Type, owner: Any? = nil) -> T { | |
return fromNib(nibName: nibName, type: T.self, owner: owner)! | |
} | |
public class func fromNib<T: UIView>(nibName: String? = nil, type: T.Type, owner: Any? = nil) -> T? { | |
var view: T? | |
let name: String | |
if let nibName = nibName { | |
name = nibName | |
} else { | |
name = self.nibName | |
} | |
if let nibViews = nibBundle.loadNibNamed(name, owner: owner, options: nil) { | |
if nibViews.indices.contains(nibIndex), let tog = nibViews[nibIndex] as? T { | |
view = tog | |
} | |
} | |
return view | |
} | |
public class var nibName: String { | |
return "\(self)".components(separatedBy: ".").first ?? "" | |
} | |
public class var nibIndex: Int { | |
return 0 | |
} | |
public class var nibBundle: Bundle { | |
return Bundle.main | |
} | |
} | |
// Use like | |
class BaseView: UIView { | |
override class var nibName: String { return "BaseView" } | |
weak var delegate: StandardStateViewDelegate? | |
} | |
class MyView: BaseView { | |
override class var nibIndex: Int { return 1 } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment