我有一個從另一個類繼承而來的叫做徽章的類,我希望建構式方法告訴通知的樣式。
但我遇到了這個錯誤:屬性 '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()
}
uj5u.com熱心網友回復:
您可以通過在 中添加一行設定notificationStyle為默認值來解決此問題init?(coder aDecoder: NSCoder):
required init?(coder aDecoder: NSCoder) {
self.notificationStyle = .numberedSquare //<-- Here
super.init(coder: aDecoder)
setup(notificationStyle: notificationStyle)
}
您必須這樣做,因為在您的 宣告中notificationStyle,沒有默認值,并且在呼叫 之前必須有一個值super.init。在您的其他初始化程式中,您根據傳入的引數設定它。
這是一個初始化程式,聽起來您無論如何都沒有使用,但是我們需要UIViews 來實作這個必需的初始化程式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/356500.html
上一篇:將影像添加到卡片和文本
下一篇:強制物件狀態不變的解決方案
