我以编程方式添加了水平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))")
}
答案 0 :(得分:2)
由于您已经在使用标签,因此它不应该成为问题。 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
}
}
答案 1 :(得分:0)
没有标签的简单解决方案。
声明属性currentButton
weak var currentButton : UIButton?
在changeView
重设currentButton
的颜色,设置sender
的颜色并将sender
指定给currentButton
。
func changeView(_ sender: UIButton)
{
currentButton?.backgroundColor = .black
currentButton = sender
sender.backgroundColor = .red
}
由于可选链接,如果currentButton
为currentButton
nil.
的颜色
答案 2 :(得分:0)
保留UIButton类型的周属性以暂时保存所选按钮。
weak var selectedButton: UIButton?
在按钮的选择器中,将selectedButton
的颜色设为默认值,然后更改新选择按钮的颜色并重置selectedButton
@IBAction func actionTouchUpInside(sender: UIButton) {
if let selectedButton = self.selectedButton {
selectedButton.backgroundColor = UIColor.clear
}
sender.backgroundColor = UIColor.blue
selectedButton = sender
}