---
title: "swift项目在iOS8 通过init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle"
author: "啸笑天"
date: "2017-06-21T19:50:57Z"
tags: []
categories: ["移动开发"]
slug: "swift-ios8-init-nibname-nibnameornil-string-bundle-nibbundleornil-bundle"
draft: false
lastmod: "2017-09-26T15:07:33Z"
id: 2380842
url: "https://justsee.iteye.com/blog/2380842"
---

[原文地址](https://github.com/easyui/blog/blob/master/iOS/2017-06-21-swift%E9%A1%B9%E7%9B%AExib%E5%9C%A8iOS8%20%E9%80%9A%E8%BF%87init%28nibName%2C%20bundle%29%E5%88%9D%E5%A7%8B%E5%8C%96%E5%A4%B1%E8%B4%A5%5BSwift3%5D.md)

 

初始化代码：

MatchViewControllerPhone(nibName:"MatchViewControllerPhone", bundle: nil)

 

MatchViewControllerPhone类部分代码：

class MatchViewControllerPhone: UIViewController 

    @IBOutlet weak var container: UIScrollView!

 // MARK: - Life cycle

    override func viewDidLoad() {

        super.viewDidLoad()

         self.container.delegate = self   //在iOS8设备上报错：fatal error: unexpectedly found nil while unwrapping an Optional value

    }

 

}

 

查看发现xib里的子控件都为nil导致的。

 

后来发现init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?)中nibNameOrNil参数在iOS8中为空，所有有以下解决方案：

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {

        let classString = String(describing: type(of: self))

        super.init(nibName: nibNameOrNil ?? classString, bundle: nibBundleOrNil)

    }

 

ps：

1、在iOS9iOS10设备上是好的，估计被苹果修复了

2、在storyboard中也是好的，所以xib换成storyboard也是可以解决的。