2017-07-04 175 views
1

我在程序中添加了一个水平的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

请发表您的代码 –

+0

我说我的源代码在这里。我必须更改changeView功能中的按钮颜色 – krishna

+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 
    } 
} 
+0

ThankYou先生,你真棒 – krishna

+0

不要忘记标记答案为接受,如果他们解决您的问题。 – Majster

+1

当然,我已经做到了 – krishna

0

简单的解决方案没有标签。

声明一个属性currentButton

weak var currentButton : UIButton? 

changeView重置currentButton的颜色,设置sender的颜色和分配给sendercurrentButton

func changeView(_ sender: UIButton) 
{ 
    currentButton?.backgroundColor = .black 
    currentButton = sender 
    sender.backgroundColor = .red 
} 

由于可选链接的currentButton颜色如果currentButtonnil.

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 
}