簡體   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