gpt4 book ai didi

ios - swift 更新类(class)

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:01:02 26 4
gpt4 key购买 nike

我正在寻找解决我的问题的方法。我有一个为我创建 UIButton 的类:

class MenuButton: UIButton {

var x: CGFloat
var y: CGFloat
var width: CGFloat
var height: CGFloat

required init(parent: UIView = UIView(), x: CGFloat = 0, y: CGFloat = 0, width: CGFloat = 40, height: CGFloat = 40) {

self.x = x
self.y = y
self.width = width
self.height = height

super.init(frame: .zero)

frame = CGRect(x: x, y: y, width: width, height: height)
backgroundColor = global.labelColor
setTitleColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)
layer.cornerRadius = self.frame.height / 2

if x < 0 {
frame = CGRect(x: superview?.frame.width ?? 0 - abs(x) - frame.width, y: frame.minY, width: frame.width, height: frame.height)
}

if y < 0 {
frame = CGRect(x: frame.minX, y: superview?.frame.height ?? 0 - abs(y) - frame.height, width: frame.width, height: frame.height)
}
}

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

然后我添加一个分配给此类的常量:

let pauseButton = MenuButton()

这很好用,按钮显示在场景中,一切都默认。现在我想在 viewDidLoad() 中添加这些东西(我添加了 subview 以在类中访问它):

view.addSubview(pauseButton)
pauseButton.x = -20
pauseButton.y = 20
pauseButton.width = 40
pauseButton.height = 40

这不会更新我在 init() 中指定的内容。我如何再次调用 init(无需再次执行 pauseButton = MenuButton())或者我可以使用 update() 之类的东西?

谢谢你的帮助;)

最佳答案

您实际上可以在初始化程序中传递这些值,如下所示,

let pauseButton = MenuButton(parent: view, x: -20, y: 20, width: 40, height: 40)

如果您想在更改这些属性时立即更新按钮,那么您可以使用 didSet 回调来设置 frame,如下所示,

class MenuButton: UIButton {

var x: CGFloat {
didSet {
self.updateFrame()
}
}

var y: CGFloat {
didSet {
self.updateFrame()
}
}

var width: CGFloat {
didSet {
self.updateFrame()
}
}

var height: CGFloat {
didSet {
self.updateFrame()
}
}

private func updateFrame() {
frame = CGRect(x: x, y: y, width: width, height: height)
}

required init(parent: UIView = UIView(), x: CGFloat = 0, y: CGFloat = 0, width: CGFloat = 40, height: CGFloat = 40) {

self.x = x
self.y = y
self.width = width
self.height = height

super.init(frame: .zero)

frame = CGRect(x: x, y: y, width: width, height: height)
backgroundColor = .green
setTitleColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)
layer.cornerRadius = self.frame.height / 2

if x < 0 {
frame = CGRect(x: superview?.frame.width ?? 0 - abs(x) - frame.width, y: frame.minY, width: frame.width, height: frame.height)
}

if y < 0 {
frame = CGRect(x: frame.minX, y: superview?.frame.height ?? 0 - abs(y) - frame.height, width: frame.width, height: frame.height)
}
}

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

关于ios - swift 更新类(class),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52966532/

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