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

时间:2015-06-16 20:05:46

标签: ios uitableview error-handling swift2 xcode7

我尝试给我的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'

我该怎么办? 非常感谢你!

3 个答案:

答案 0 :(得分:12)

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

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

答案 1 :(得分:0)

    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")
    }

我希望这会对你有用Override init method of UIView in swift

答案 2 :(得分:0)

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

例如,我尝试创建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;

希望这会有所帮助。