gpt4 book ai didi

ios - Swift 中 2 个初始值设定项的奇怪问题

转载 作者:行者123 更新时间:2023-11-28 12:01:22 25 4
gpt4 key购买 nike

我想为我的自定义按钮类创建 2 个初始化器,如下所示:

protocol CustomButtonProtocol {
var title: String { get set }
var cornerRadius: CGFloat { get set }
var backgroundColor: UIColor { get set }
}

struct Button: CustomButtonProtocol {
var title: String
var cornerRadius: CGFloat
var backgroundColor: UIColor
}

class CustomButton: UIButton {
var title: String? {
didSet {
self.setTitle(title, for: .normal)
}
}

var cornerRadius: CGFloat = 0.0 {
didSet {
self.layer.cornerRadius = cornerRadius
}
}

var color: UIColor? {
didSet {
self.backgroundColor = color
}
}

override init(frame: CGRect) {
super.init(frame: frame)
}

init(with frame: CGRect, button: Button) {
super.init(frame: frame)

self.title = button.title
self.cornerRadius = button.cornerRadius
self.backgroundColor = button.backgroundColor
}

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

我想要 2 个初始化器,第一个是简单的初始化器,第二个是我的 Button 传入的,但问题是它只改变背景颜色但不改变 title cornerRadius 属性,我找不到它发生的原因。也许我没有看到什么,你能帮我找到错误吗?

最佳答案

您已使用 didSet 更新按钮属性的值。

init 中设置值时不会调用 didSet

正在设置背景颜色,因为您错误地将 backgroundColor 设置为 color

self.backgroundColor = button.backgroundColor

您应该在 init 内部/外部使用/调用一次。

self.setTitle(title, for: .normal)
self.layer.cornerRadius = cornerRadius
self.backgroundColor = color

关于ios - Swift 中 2 个初始值设定项的奇怪问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50060890/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com