美文网首页
swift:如何从xib获取self,loadNib实例化Vie

swift:如何从xib获取self,loadNib实例化Vie

作者: 半江瑟瑟 | 来源:发表于2016-09-22 17:18 被阅读1868次
Paste_Image.png
class func showHUDAddedToWindowWithText(text: String) -> LEAlertHud {
    let alertHud = self.loadFromNib()
    alertHud.alertContentLabel.text = text
    alertHud.initUI()
    return alertHud
}
Paste_Image.png
// MARK: - How to initialise a UIView Class with a xib file in Swift
extension UIView {
class func loadFromNibNamed(nibNamed: String, bundle : NSBundle? = nil) -> UIView? {
    return UINib(
        nibName: nibNamed,
        bundle: bundle
        ).instantiateWithOwner(nil, options: nil)[0] as? UIView
    }
}

protocol UIViewLoading {}
extension UIView : UIViewLoading {}
extension UIViewLoading where Self : UIView {
// note that this method returns an instance of type `Self`, rather than UIView
static func loadFromNib() -> Self {
    let nibName = "\(self)".characters.split{$0 == "."}.map(String.init).last!
    let nib = UINib(nibName: nibName, bundle: nil)
    return nib.instantiateWithOwner(self, options: nil).first as! Self
}

}
参考文章:
http://stackoverflow.com/questions/24370061/assign-xib-to-the-uiview-in-swift
http://stackoverflow.com/questions/25513271/how-to-initialise-a-uiview-class-with-a-xib-file-in-swift-ios

作者声明:我是小菜鸟,文章内容仅是自己在工作中总结、同事们的指导和网络搜索,难免有疏漏错误,大神们应用之后没有解决问题,我很抱歉;如能即时提出予以雅正,不胜感激.谢绝发泄式差评.欢迎交流分享,祝好.

相关文章

网友评论

      本文标题:swift:如何从xib获取self,loadNib实例化Vie

      本文链接:https://www.haomeiwen.com/subject/embzettx.html