美文网首页ios专题
(Swift下)ios8Controller关联xib

(Swift下)ios8Controller关联xib

作者: 云智真人 | 来源:发表于2016-06-29 10:51 被阅读555次

ios8.x下要让Controller能与xib关联,关键是init(nibNameOrNil, bundleOrNil)方法。既然子类没有自动继承,我们就需要添加相关代码。(ios9及后续版本会自动继承方法找到对应的xib不需要重写),代码如下:

override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
    let classString = String(self.dynamicType)
    if NSBundle.mainBundle().pathForResource(classString, ofType: "nib") == nil {
        print("n-xib")
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)

    } else {
        print("xib")
        super.init(nibName: nibNameOrNil ?? classString, bundle: nibBundleOrNil)
    }
}
    
required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

  • 这里需要注意的是Bundle中xib是以nib为后缀存储的

StackOverflow下还给出了另一种解决办法

@objc(MyViewController) class MyViewController: UIViewController {}

相关文章

网友评论

    本文标题:(Swift下)ios8Controller关联xib

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