加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift iOS8 XIB 问题 ViewController.init() xib

发布时间:2020-12-14 06:44:19 所属栏目:百科 来源:网络整理
导读:对于OC 中 ViewController *vc = [[ViewController alloc] init],方法默认会加载一个同名的xib文件当View。但是在swift中 ViewController.init() 在 iOS8 上他不会默认加载xib,而在iOS 9 中却默认加载了 xib。 前段时间工程一直在iOS9 + 环境的真机上调试,

对于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中的内容。

[objc] view plain copy
  1. funcapplication(application:UIApplication,didFinishLaunchingWithOptionslaunchOptions:[NSObject:AnyObject]?)->Bool{
  2. self.window=UIWindow(frame:UIScreen.mainScreen().bounds)
  3. self.window?.makeKeyAndVisible()
  4. letvc=myViewController()
  5. letnavigation=UINavigationController.init(rootViewController:vc)
  6. self.window?.rootViewController=navigation
  7. returntrue
  8. }

2,我们需要在找到XIB,在初始化的时候,需要使用nib的方法。这样可以显示正常。

copy
    letvc:myViewController?=myViewController(nibName:"myViewController",bundle:nil)
  1. letnavigation=UINavigationController.init(rootViewController:vc!)
  2. true
  3. }


copy
    classmyViewController:UIViewController{
  1. @IBOutletweakvartitleLab:UILabel!
  2. overrideinit(nibNamenibNameOrNil:String!,bundlenibBundleOrNil:NSBundle!){
  3. super.init(nibName:nibNameOrNil,0); background-color:inherit">bundle:nibBundleOrNil)
  4. }
  5. requiredinit?(coderaDecoder:NSCoder){
  6. fatalError("init(coder:)hasnotbeenimplemented")
  7. overridefuncviewDidLoad(){
  8. super.viewDidLoad()
  9. titleLab.text="这是什么事啊!!!!!"
  10. overridefuncdidReceiveMemoryWarning(){
  11. super.didReceiveMemoryWarning()
  12. //DispoSEOfanyresourcesthatcanberecreated.
  13. }

解决方案
1. 通过加载 xib的方式来初始化ViewController (取代默认的 ViewController.init())

2.重写 init() 方法

//3.重写无参数初始化方法,自动调用xib文件

convenienceoverrideinit() {

varnibNameOrNil =String?("RootViewController")

//考虑到xib文件可能不存在或被删,故加入判断

ifNSBundle.mainBundle().pathForResource(nibNameOrNil,ofType:"xib") ==nil

{

nibNameOrNil =nil

}

self.init(nibName: nibNameOrNil,bundle:nil)

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读