我正在尝试在 viewController
中添加 subview 。为了执行此操作,我创建了一个 xib 文件和关联的类。关联类的代码如下:
import UIKit
@IBDesignable class CustomClassViewController: UIView {
@IBOutlet weak var myLabel: UILabel!
var Dummyview : UIView! //= UIView()
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init (coder aDecoder : NSCoder){
super.init(coder : aDecoder)!
setup()
}
func setup() {
Dummyview = loadViewFromNib()
Dummyview.frame = bounds
Dummyview.autoresizingMask = UIViewAutoresizing.FlexibleWidth
Dummyview.autoresizingMask = UIViewAutoresizing.FlexibleHeight
addSubview(Dummyview)
}
func loadViewFromNib() -> UIView {
let bundle = NSBundle(forClass : self.dynamicType)
let nib = UINib(nibName: "Custom View", bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
return view
}
在运行应用程序之前它没有显示任何错误,但是当我运行应用程序时它崩溃了。错误如下:
"Threat 1: EXC_BAD_ACCESS(code= 2, address= 0x7fff52776e88)"
super.init(编码器:aDecoder)!
但是输出没有错误。
我已经尝试过 here 中提供的解决方案和 here但没有成功。
我该怎么办?有什么解决办法吗?请告诉我。 提前致谢
最佳答案
使用编码器初始化可能会失败,您不应该在那里使用强制解包。请尝试以下操作:
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
此外,您的类 CustomClassViewController 是 UIView 的子类,而不是 UIViewController。更改此行
@IBDesignable class CustomClassViewController: UIView {
到
class CustomClassViewController: UIViewController {
注意: View Controller 不能是 IBDesignable
关于ios - 调用 Super.init(编码器 : aDecoder)) 时应用程序突然崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40481193/