在 CustomUIView 中重写 init() 会导致应用程序崩溃(EXC_BAD ACCESS)

2023-11-25

我正在尝试在 Swift 中子类化 UIView。

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

这是班级

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() 替换 self.init() 但无法编译。

错误信息:

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

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


你需要用一个框架来初始化你的 UIVIew,即使它是零,你也需要重写 init,这样你就可以在调用 super 之前初始化你的变量:

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();
    }
}

请注意,我删除了您创建的其他便利初始化程序,因为所有变量都是私有的,因此不需要此初始化程序,但是如果您想要一个空的初始化程序,您只需添加为:

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

框架的大小也可以传递或修复,您只需要进行适当的更改并调用init(frame: yourFrame)

初始化规则来自苹果文档:

规则 1 指定初始化程序必须调用指定初始化程序 来自它的直接超类。

规则 2 便利初始化器必须调用另一个初始化器 同一个班级。

规则 3 便利初始化程序必须最终调用指定的 初始化程序。

记住这一点的一个简单方法是:

指定的初始化器必须始终向上委托。方便 初始化器必须始终委托。

enter image description here

我希望这对你有帮助!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 CustomUIView 中重写 init() 会导致应用程序崩溃(EXC_BAD ACCESS) 的相关文章

随机推荐