在CustomUIView中覆盖init()崩溃应用程序(EXC_BAD ACCESS)

我想在Swift中inheritance一个UIView。

当初始化程序被调用时,应用程序崩溃(EXC_BAD_ACCESS)

这是class级

class CustomActionSheet: UIView { private var cancelButtonTitle: String!; private var destructiveButtonTitle: String!; private var otherButtonTitles: [String]!; convenience init() { self.init();//EXC_BAD_ACCESS } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder); } convenience init(cancelButtonTitle: String!, destructiveButtonTitle: String!, otherButtonTitles: [String]!) { self.init(); self.cancelButtonTitle = cancelButtonTitle; self.destructiveButtonTitle = destructiveButtonTitle; self.otherButtonTitles = otherButtonTitles; prepareUI(); } func prepareUI() { //BLABLABLABLABLA } } 

这是我如何称呼它

  var actionSheet: CustomActionSheet = CustomActionSheet(cancelButtonTitle: "Cancel", destructiveButtonTitle: "OK", otherButtonTitles: nil); 

任何想法??????

更新:

试图用super.init()replaceself.init(),但它不会编译。

错误信息 :

必须调用超类“UIView”的指定初始值设定项

“CustomActionSheet”的便利初始值设定项必须委托(使用'self.init')而不是链接到超类初始化程序(使用'super.init')

你需要用一个框架来初始化你的UIVIew,即使它是零,你也需要覆盖init,以便在调用supper之前初始化你的variables:

 class CustomActionSheet: UIView { private var cancelButtonTitle: String!; private var destructiveButtonTitle: String!; private var otherButtonTitles: [String]!; override init(frame: CGRect) { cancelButtonTitle = String() destructiveButtonTitle = String() otherButtonTitles: [String]() super.init(frame:frame) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder); } convenience init(cancelButtonTitle: String!, destructiveButtonTitle: String!, otherButtonTitles: [String]!) { self.init(frame: CGRectZero) self.cancelButtonTitle = cancelButtonTitle; self.destructiveButtonTitle = destructiveButtonTitle; self.otherButtonTitles = otherButtonTitles; prepareUI(); } } 

注意我删除了你创build的其他便利初始值设定项,因为所有的variables都是私有的,不需要这个初始值设定项,但是如果你想有一个空的初始值设定项,你可以添加如下:

 convenience init() { self.init(frame: CGRectZero) } 

此外,帧的大小可以通过或修复你只需要作出适当的改变,并调用init(frame: yourFrame)

Apple文档初始化规则:

规则1指定的初始化程序必须从其直接的超类中调用指定的初始化程序。

规则2一个便捷初始值设定项必须调用同一个类的另一个初始值设定项。

规则3便利初始值设定项最终必须调用指定的初始值设定项。

记住这个简单的方法是:

指定的初始值设定项必须总是委托。 便捷初始值设定项必须始终进行委托。

在这里输入图像说明

我希望能帮到你!