Xcode:如何使用类从主视图控制器重置所有按钮的状态
我有一个按钮类,当按下按钮时会改变颜色,在开和关之间交替Xcode:如何使用类从主视图控制器重置所有按钮的状态,xcode,swift4,Xcode,Swift4,我有一个按钮类,当按下按钮时会改变颜色,在开和关之间交替 class KSPickButton: UIButton { var isOn = true override init(frame: CGRect) { super.init(frame: frame) initButton() } required init?(coder aDecoder: NSCoder) { super.init(coder:
class KSPickButton: UIButton {
var isOn = true
override init(frame: CGRect) {
super.init(frame: frame)
initButton()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initButton()
}
func initButton() {
layer.borderWidth = 2.0
layer.borderColor = Colors.shanklinGreen.cgColor
layer.cornerRadius = frame.size.height/2
backgroundColor = .clear
setTitleColor(.white, for: .normal)
addTarget(self, action: #selector(KSPickButton.buttonPressed), for: .touchUpInside)
}
@objc func buttonPressed() {
activateButton(bool: !isOn)
}
func activateButton(bool: Bool) {
isOn = bool
let color = bool ? .clear : Colors.shanklinGreen
//let title = bool ? "" : ""
let titleColor = bool ? .white: Colors.shanklinBlack
//setTitle(title, for: .normal)
setTitleColor(titleColor, for: .normal)
backgroundColor = color
}
}
这很好用。我的主视图控制器上有20个按钮,它们按预期在打开和关闭之间切换。。。然后可能在按6之后,我想将它们全部重置为off。我的主视图控制器上有一个重置按钮,但我无法确定如何将它们全部重置
我可以让它们看起来都重置了,但是bool保持原样
如何为所有按钮调用此类并正确重置它们?引入了一个带有“isOn”变量的观察者。您可以尝试在“KSPickButton”类中使用以下代码段。之后,您需要从视图控制器(按钮所在的位置)获取所有子视图,并将所有子视图的“isOn”设置为“false”
class KSPickButton: UIButton {
public var isOn:Bool = true {
didSet {
handleButtonStateChange()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
initButton()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initButton()
}
func initButton() {
layer.borderWidth = 2.0
layer.borderColor = Colors.shanklinGreen.cgColor
layer.cornerRadius = frame.size.height/2
backgroundColor = .clear
setTitleColor(.white, for: .normal)
addTarget(self, action: #selector(KSPickButton.buttonPressed), for: .touchUpInside)
}
@objc func buttonPressed() {
isOn = !isOn
}
func handleButtonStateChange() {
let color = isOn ? .clear : Colors.shanklinGreen
let titleColor = isOn ? .white: Colors.shanklinBlack
setTitleColor(titleColor, for: .normal)
backgroundColor = color
}
}
下面是您需要在视图控制器中实现的代码片段,如上所述
class MyVC: UIViewController {
------
------
for subview in view.subviews where subview.isKind(of: KSPickButton.self)&&(subview as? KSPickButton)?.isOn == true {
(subview as? KSPickButton)?.isOn = false
}
-----
-----
}
为了更清楚,请包括添加按钮到VC的代码和重置按钮操作代码。目前,按钮是手动放置的,我还没有重置代码。我在想也许我应该使用代码添加这些按钮,然后在我重置时调用这些代码。。我们将考虑这一选择。谢谢