ios - 调用 Super.init(编码器 : aDecoder)) 时应用程序突然崩溃

标签 ios swift xcode7 subview

我正在尝试在 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/

相关文章:

ios - UILabel具有自动布局的丑陋旋转动画

xcode - 重构 ViewControllers - 错误 : Storyboard both contain a view controller with same identifier

ios - 快速多点连接,使用邀请处理程序取消邀请

xcode - 在 Swift 中从 Firebase 获取单独的数据

ios - 新的 Facebook SDK 3.20 和 iOS 5.1.1 崩溃

ios - estimatedHeightForRowAtIndexPath 和 heightForRowAtIndexPath 之间的区别?

json - 如何从字典数组中按键选择数据?

ios - 如何在 Swift 中显示动态高度的 3*3 CollectionView 单元格

ios - 以编程方式禁用 IOS 3d 触摸手势

ios - 如何将自定义单元格设置为 UITableView 的页眉或页脚