swift - 在 iOS 8 上呈现 NIB 模态崩溃,但在 iOS 9+ 上不会

标签 swift xcode crash nib

我创建了一个名为 SomeViewController 的 NIB,所有相应的代码都是正确的,所有的 View 都正确绑定(bind),但不知何故代码 self.presentViewController(SomeViewController() , animated: true, completion: nil) 导致崩溃:

fatal error: unexpectedly found nil while unwrapping an Optional value

问题是什么?

最佳答案

为了解决这个问题,我们需要通过这样做来检查版本

    if #available(iOS 8, *) {
        self.presentViewController(SomeViewController(nibName: "SomeViewController", bundle: nil), animated: true, completion: nil)
    } else {
        self.presentViewController(SomeViewController(), animated: true, completion: nil)
    }

或者只是

self.presentViewController(SomeViewController(nibName: "SomeViewController", bundle: nil), animated: true, completion: nil)

出于某种原因,iOS 8 不会自动在初始化时将 nibName 包含在其对应的类中。

更新:

也可以通过这样做来修复

class SomeViewController: UIViewController {
    init() {
        super.init(nibName: "SomeViewController'sNibNameHere", bundle: nil)
    }
}

// on some other part of your code
self.presentViewController(SomeViewController(), animated: true, completion: nil)

关于swift - 在 iOS 8 上呈现 NIB 模态崩溃,但在 iOS 9+ 上不会,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40860839/

相关文章:

ios - 如何使用工厂设计模式使用自定义参数初始化 View Controller

iphone - 连续切换 Sprite 图像(不显示动画)

android - “GET GOOGLE PLAY SERVICES”单击时,ActivityNotFoundException崩溃(以小米设备为例)

ios - map View :rendererForOverlay delegate method never called when addOverlay is called on MKMapView

ios - 如何使用 IBAction 将数据写入 Firebase

ios - 无法导入桥接头 '/MyProject-Bridging.h'

ios - 在 iOS 中的选项卡栏上显示自定义 View

ios - 使用 Swift 和 Cocoapods 的框架在其 Info.plist 中没有 CFBundleIdentifier

c++ - gdb条件中断中使用的STL类型/函数,会导致程序崩溃吗?

c++ - 在 VC++2010 环境之外运行时程序立即崩溃