OGeek|极客世界-中国程序员成长平台

标题: ios - 如果我在 iOS8 模拟器上运行应用程序,则不会初始化来自 xib 的 IBOutlets [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 11:42
标题: ios - 如果我在 iOS8 模拟器上运行应用程序,则不会初始化来自 xib 的 IBOutlets

我已经使用 XCode 7 GM(基础 SDK - iOS9)构建了一个应用程序。如果我在 iOS 9 模拟器上运行它可以完美运行,但如果我尝试在 iOS8 上运行它会失败:

@IBOutlet weak var collectionView: UICollectionView!

override func viewDidLoad() {
    super.viewDidLoad()
    navigationItem.title = NSLocalizedString("Home", comment: "Home")
    collectionView.registerNib(UINib(nibName: "THomeCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "THomeCollectionViewCell")
}

有错误

fatal error: unexpectedly found nil while unwrapping an Optional value

因为 collectionView 是 nil: enter image description here

当然,我已经检查了 IB 中的连接是否已建立: enter image description here

谁能告诉我为什么collectionView在这里是零?



Best Answer-推荐答案


我可以通过添加来解决这个问题

override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
    let name = NSStringFromClass(self.dynamicType).componentsSeparatedByString(".").last!
    super.init(nibName: nibNameOrNil ?? name, bundle: nibBundleOrNil)
}

到 View Controller 类。但是为什么它会这样工作呢?有没有其他方法可以解决这个问题?

更新: 这是一个 Swift View Controller 功能,与 bug 非常相似。查看 Can't Load UIViewController XIB file in Storyboard in SwiftAre view controllers with nib files broken in ios 8 beta 5?

它在 iOS 9.4 中已修复,但如果您需要 iOS 8 及更早版本的支持,您仍需要使用变通方法。

关于ios - 如果我在 iOS8 模拟器上运行应用程序,则不会初始化来自 xib 的 IBOutlets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32632421/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4