对于OC 中 ViewController *vc = [[ViewController alloc] init],方法默认会加载一个同名的xib文件当View。但是在swift中 ViewController.init() 在 iOS8 上他不会默认加载xib,而在iOS 9 中却默认加载了 xib。
前段时间工程一直在iOS9 + 环境的真机上调试,今天拿iOS8的机子调试,发现所有使用XIB创的 ViewController都不可用。甚至因为可选类型而到时奔溃。无奈之下,重新建一个测试demo,找问题。终于解决了这个问题。
1,在AppDelegate中,如果这样写,因为不使用storyboard,而使用XIB,在iOS8中,无法显示XIB中的内容。
- func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
-
- self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
- self.window?.makeKeyAndVisible()
-
- let vc = myViewController()
- let navigation = UINavigationController.init(rootViewController: vc)
- self.window?.rootViewController = navigation
-
- return true
- }
2,我们需要在找到XIB,在初始化的时候,需要使用nib的方法。这样可以显示正常。
- func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
-
- self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
- self.window?.makeKeyAndVisible()
-
- let vc: myViewController? = myViewController(nibName: "myViewController", bundle: nil)
- let navigation = UINavigationController.init(rootViewController: vc!)
- self.window?.rootViewController = navigation
-
-
- return true
- }
- class myViewController: UIViewController {
-
- @IBOutlet weak var titleLab: UILabel!
- override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
- super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
- }
-
- required init?(coder aDecoder: NSCoder) {
- fatalError("init(coder:) has not been implemented")
- }
- override func viewDidLoad() {
- super.viewDidLoad()
- titleLab.text = "这是什么事 啊!!!!!"
- }
-
- override func didReceiveMemoryWarning() {
- super.didReceiveMemoryWarning()
-
- }
-
解决方案
1. 通过加载 xib的方式来初始化ViewController (取代默认的 ViewController.init())
2.重写 init() 方法
//3.重写无参数初始化方法,自动调用xib文件
convenience override init() {
var nibNameOrNil = String?("RootViewController")
//考虑到xib文件可能不存在或被删,故加入判断
if NSBundle.mainBundle().pathForResource(nibNameOrNil, ofType: "xib") == nil
{
nibNameOrNil = nil
}
self.init(nibName: nibNameOrNil, bundle: nil)
}