gpt4 book ai didi

swift - 如何更改点击的一对按钮的颜色?

转载 作者:行者123 更新时间:2023-11-28 09:31:55 27 4
gpt4 key购买 nike

我有 3 对按钮,名称为 (one,numOne),(two,numTwo),(three,numThree)。所有按钮的初始 tintColor 都是 black。我喜欢将这对按钮的颜色更改为 blue,如果它们中的一个按钮被点击,当另一对按钮被点击时返回到 black。我可以通过以下代码来完成,但是除了下面还有其他最短的方法吗?

@IBOutlet weak var one: UIButton!
@IBOutlet weak var two: UIButton!
@IBOutlet weak var three: UIButton!
@IBOutlet weak var numOne: UIButton!
@IBOutlet weak var numTwo: UIButton!
@IBOutlet weak var numThree: UIButton!

@IBAction func buttonTapped(_ sender: UIButton) {
if sender == one || sender == numOne
{
one.tintColor = UIColor.blue
numOne.tintColor = UIColor.blue
two.tintColor = UIColor.black
numTwo.tintColor = UIColor.black
three.tintColor = UIColor.black
numThree.tintColor = UIColor.black

}
else if sender == two || sender == numTwo
{
two.tintColor = UIColor.blue
numTwo.tintColor = UIColor.blue
one.tintColor = UIColor.black
numOne.tintColor = UIColor.black
three.tintColor = UIColor.black
numThree.tintColor = UIColor.black

}
else
{
three.tintColor = UIColor.blue
numThree.tintColor = UIColor.blue
two.tintColor = UIColor.black
numTwo.tintColor = UIColor.black
one.tintColor = UIColor.black
numOne.tintColor = UIColor.black

}
}

最佳答案

var allButtons: [[UIButton]] = [[one, numOne], [two, numTwo], [three, numThree]]

func tap(_ sender: UIButton) {
allButtons.forEach { buttons in
if buttons.contains(sender) {
buttons.forEach{ $0.tintColor = .blue }
} else {
buttons.forEach{ $0.tintColor = .black }
}
}
}

更短的XD

buttons.contains(sender) ? buttons.forEach{ $0.tintColor = .blue } : buttons.forEach{ $0.tintColor = .black }

关于swift - 如何更改点击的一对按钮的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41376285/

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