[Swift]ViewController中xib控件为空
2016-06-21 12:31
671 查看
在ViewController的xib中定义了一些控件,然后在使用的时候会因为这个控件为空而崩溃,报错为:
What?
解决办法如下:
1.首先要保证正确初始化了ViewController,使用初始化方法 init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) 初始化视图控制器(OC中对应 -(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil),OC中直接使用init也是可以的,这时系统会自动调用initWithNibName 方法。
2.在viewDidLoad方法加载之前,这些xib的控件是可能为空的,所以在变量的属性观察器中使用xib控件时要注意。如:
应当在viewDidLoad之后使用这些控件。
Swift Error fatal error: unexpectedly found nil while unwrapping an Optional value
What?
解决办法如下:
1.首先要保证正确初始化了ViewController,使用初始化方法 init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) 初始化视图控制器(OC中对应 -(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil),OC中直接使用init也是可以的,这时系统会自动调用initWithNibName 方法。
/* The designated initializer. If you subclass UIViewController, you must call the super implementation of this method, even if you aren't using a NIB. (As a convenience, the default init method will do this for you, and specify nil for both of this methods arguments.) In the specified NIB, the File's Owner proxy should have its class set to your view controller subclass, with the view outlet connected to the main view. If you invoke this method with a nil nib name, then this class' -loadView method will attempt to load a NIB whose name is the same as your view controller's class. If no such NIB in fact exists then you must either call -setView: before -view is invoked, or override the -loadView method to set up your views programatically. */ - (instancetype)initWithNibName:(nullable NSString *)nibNameOrNil bundle:(nullable NSBundle *)nibBundleOrNil
2.在viewDidLoad方法加载之前,这些xib的控件是可能为空的,所以在变量的属性观察器中使用xib控件时要注意。如:
var naviTitle :String?{ didSet{ naviView.title = naviTitle } }
应当在viewDidLoad之后使用这些控件。
相关文章推荐
- [Swift]ViewController中xib控件为空
- Swift必备开发库(高级篇)
- Swift必备开发库(高级篇)
- push 相关积累
- Swift 实现图片转字符画的功能
- Swift 算法实战之路:栈和队列
- Swift-基础-7
- GlusterFS替代OpenStack 的swift模块
- Swift - 告警提示框(UIAlertController)的用法
- Swift - 滑块(UISlider)的用法
- Swift - 进度条(UIProgressView)的用法
- Swift - 图像控件(UIImageView)的用法
- Swift - 分段选择控件(UISegmentedControl)的用法
- Swift - 开关按钮(UISwitch)的用法
- swift Array 数组
- swift2.0 学习笔记Eighteen
- swift学习代码笔记
- swift项目中极光推送
- Swift - 文本输入框(UITextField)的用法
- Swift - 文本标签(UILabel)的用法