required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
在swift中继承UIView的子类时候,会要求写required init这个方法,一般我就如上写,并没有出过什么问题。
今天用story board创建collection view,自定义collection view cell,也如上写required init .....但是运行的时候抛出fatal error
fatal error: init(coder:) has not been implemented
这不就是我如上写的那句fatal error 么
于是查这是什么东西,在stackoverflow上面找到了如下答案
http://stackoverflow.com/questions/24036393/fatal-error-use-of-unimplemented-initializer-initcoder-for-class
This is caused by the absence of the initializer init(coder aDecoder: NSCoder!)
on the target UIViewController
That method is required because instantiating a UIViewController from a UIStoryboard calls it.
To see how do we initialize UIViewController
from a UIStoryboard
please take a look here
Why is this not a problem on Objective-C?
Because Objective-C automatically inherits all the required UIViewController
initializers.
Why does not Swift automatically inherit the initializers?
Swift by default does not inherit the initializers due to safety. But it will inherit all the initializers from the superclass if all the properties have a value (or optional) and the subclass has not defined any designated initializers.
Solution
- First method
Manually implementing init(coder aDecoder: NSCoder!)
on the target UIViewController
init(coder aDecoder: NSCoder!) { super.init(coder: aDecoder)} - Second method
Removing init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?)
on your target UIViewController
will inherit all of the required initializers from the superclass asDave Wood pointed on his answer below
网友评论