gpt4 book ai didi

ios - 按下下一个按钮时如何更改上一个按钮的颜色?

转载 作者:行者123 更新时间:2023-12-01 19:52:38 25 4
gpt4 key购买 nike

我在水平UIScrollView中以编程方式添加了许多按钮。我必须更改用户选择的按钮的颜色。但是,如果用户选择另一个按钮,则先前的按钮颜色必须更改为默认颜色。
我怎样才能做到这一点?请帮我...

func createHorizontalScroll()
{
let scrollView = UIScrollView(frame: CGRect(x: CGFloat(0), y: CGFloat(410), width: CGFloat(view.frame.size.width), height: CGFloat(40)))

var buttonX: CGFloat = 0

for index in 0..<btnNames.count
{
//add an element and the previous element together
let sum = btnNames[index]

button = UIButton(frame: CGRect(x: CGFloat(buttonX), y: CGFloat(0), width: CGFloat(100), height: CGFloat(40)))

print("btnNames:\(sum)")

button.setTitle("\(sum)",for:.normal)
button.layer.borderWidth = 2.5
button.layer.borderWidth = 2.5
button.layer.borderColor = UIColor.white.cgColor
button.layer.backgroundColor = UIColor.black.cgColor
button.tag = index
scrollView.addSubview(button)
buttonX = button.frame.size.width + buttonX

button.addTarget(self, action: #selector(changeView), for: .touchUpInside)
}

scrollView.contentSize = CGSize(width: CGFloat(buttonX), height: CGFloat(scrollView.frame.size.height))
scrollView.backgroundColor = UIColor.clear
view.addSubview(scrollView)
}

func changeView(_ sender: UIButton)
{
print("I Clicked a button \(Int(sender.tag))")
}

最佳答案

由于您已经在使用标签,所以这不成问题。 changeView函数应如下所示:

func changeView(_ sender: UIButton)
{
let scrollView = sender.superview as! UIScrollView //This is mildly hacky - store your scroll view in an instance variable
for view in scrollView.subviews {
guard let button = view as? UIButton else {
continue
}

button.backgroundColor = sender.tag == button.tag ? UIColor.red : UIColor.black
}
}

关于ios - 按下下一个按钮时如何更改上一个按钮的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44898061/

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