我正在寻找解决问题的方法。我有一个为我创建 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() 的方法?
感谢您的帮助;)
Best Answer-推荐答案 strong>
您实际上可以在初始化程序中传递这些值,如下所示,
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 - 快速更新类(class),我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/52966532/
|