Presenting a NIB Modally Crashes on iOS 8 but not

2019-09-05 18:00发布

I have created a NIB which has a name of SomeViewController and all the corresponding code are correct and all the views are bound correctly, but somehow the code self.presentViewController(SomeViewController(), animated: true, completion: nil) causes a crash:

fatal error: unexpectedly found nil while unwrapping an Optional value

What is the problem?

1条回答
甜甜的少女心
2楼-- · 2019-09-05 18:28

To fix this we need to version check by doing this

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

or just

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

for some reason iOS 8's not automated on including the nibName on initialization with it's corresponding class.

Update:

Can also be fixed by doing this

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)
查看更多
登录 后发表回答