簡體   English   中英

swift 屬性未在 super.init 調用中初始化

[英]swift Property not initialized at super.init call

我有一個從另一個類繼承而來的叫做徽章的類,我希望構造函數方法告訴通知的樣式。

但我遇到了這個錯誤:屬性 'self.notificationStyle' not initialized at super.init call

DefaultTableViewCell 類

final public class DefaultTableViewCell: UITableViewCell

enum NotificationStyle {
        case numberedSquare, circle
    }
    
    var notificationStyle: NotificationStyle = .numberedSquare

我的目標是每當有人實例化這個 Badge 類時,有必要通知它的 notificationStyle,在這種情況下是方形或圓形。

我該如何解決這個問題?

徽章等級

@objc public class Badge: NotifyLabel

var notificationStyle: DefaultTableViewCell.NotificationStyle

init(frame: CGRect, notificationStyle: DefaultTableViewCell.NotificationStyle) {
        self.notificationStyle = notificationStyle
        super.init(frame: frame)
        setup(notificationStyle: notificationStyle)
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup(notificationStyle: notificationStyle)
    }
    
    init(notificationStyle: DefaultTableViewCell.NotificationStyle) {
        self.notificationStyle = notificationStyle
        super.init(frame: .zero)
        setup(notificationStyle: notificationStyle)
    }

func configureBadgeNotificationStyle(notificationStyle: DefaultTableViewCell.NotificationStyle) {
        textAlignment = NSTextAlignment.center
        layer.borderWidth = 1
        layer.borderColor = Color.bostonRed.cgColor
        clipsToBounds = true
        textStyle = .label
        backgroundColor = Color.white
        
        switch notificationStyle {
        case .circle:
            layer.cornerRadius = 8
        default:
            layer.cornerRadius = 2
        }
    }
    
    private func setup(notificationStyle: DefaultTableViewCell.NotificationStyle) {
        configureBadgeNotificationStyle(notificationStyle: notificationStyle)
        configureAccessibility()
    }


通知標簽類

public class NotifyLabel: UILabel

public init(textStyle: TextStyle) {
        self.textStyle = textStyle
        super.init(frame: .zero)
        applyTextStyle()
    }
    
    public override init(frame: CGRect) {
        super.init(frame: frame)
        applyTextStyle()
    }
    
    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        applyTextStyle()
    }

您可以通過在init?(coder aDecoder: NSCoder)添加一行將notificationStyle設置為默認值來解決此問題:

required init?(coder aDecoder: NSCoder) {
    self.notificationStyle = .numberedSquare //<-- Here
    super.init(coder: aDecoder)
    setup(notificationStyle: notificationStyle)
}

您必須這樣做,因為在您的notificationStyle聲明中,沒有默認值,並且在調用super.init之前它必須有一個值。 在您的其他初始化程序中,您根據傳入的參數設置它。

這是一個初始化程序,聽起來您無論如何都沒有使用,但是UIView需要我們實現這個必需的初始化程序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM