繁体   English   中英

从初始化程序返回之前不会调用Super.init

[英]Super.init isn't called before returning from initializer

我尝试给我的UITableViewCell类一个自定义的启动器,但我无法弄清楚我做错了什么。

这是我的代码:

init(dataObject: [NSManagedObject]!, objectAttributeValues: [String]!,placeholder: String!, segmentedControl: UISegmentedControl?, cellHeight: CGRect, cellWidth: CGRect) {
    self.dataObject = dataObject
    self.Placeholder.text = placeholder
    self.objectAttributeValues = objectAttributeValues

    if segmentedControl != nil {
        self.segmentedControl = segmentedControl!
        didHaveSegmentedControl = true
    }

}

required init(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

我试着调用super.init(frame:CGRect(...))但是通过实现这个我得到另一个错误: 必须调用超类“UITableViewCell”的指定初始化器

我能做什么? 非常感谢!

初始化程序的工作方式是,它们将自己的属性,常量和函数添加到该实例,然后回调超类以获取其类型的对象。 更多信息在这里

因此,您必须在退出初始化程序之前调用超类的初始化程序。 在这里,我建议你在你的初始化的最后一行调用super.init() 您可以选择UITableViewCell上哪个init方法最合适。

    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    convenience init(frame: CGRect, dataObject: [NSManagedObject]!, objectAttributeValues: [String]!,placeholder: String!, segmentedControl: UISegmentedControl?, cellHeight: CGRect, cellWidth: CGRect){
        self.init(frame: frame)
        self.dataObject = dataObject
        self.Placeholder.text = placeholder
        self.objectAttributeValues = objectAttributeValues

        if segmentedControl != nil {
            self.segmentedControl = segmentedControl!
            didHaveSegmentedControl = true
        }

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

我希望这能帮助你在swift中覆盖UIView的init方法

您必须调用超类指定的初始化程序。

例如,我试图创建一个UIView的子类,并且遇到了完全相同的问题。 UIView的指定初始化程序是super.init(frame: CGRect)对于UITableViewCell ,指定的初始值设定项如下。

// Designated initializer.  If the cell can be reused, you must pass in a reuse 
identifier.  You should use the same reuse identifier for all cells of the same 
form.  
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier: 
(nullable NSString *)reuseIdentifier NS_AVAILABLE_IOS(3_0) 
NS_DESIGNATED_INITIALIZER;
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder 
NS_DESIGNATED_INITIALIZER;

希望这有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM