Reputation: 23
I have a number of buttons in a horizontal UIScrollView
added programmatically. I have to change the color of the user selected button. But if user select another button the previous button color must be change to default color.
how can I do this? Please help me...
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))")
}
Upvotes: 1
Views: 121
Reputation: 122
Keep a week property of type UIButton to temporally save the selected button.
weak var selectedButton: UIButton?
In the selector for your buttons make the color of the selectedButton
to default, then change the color of the newly selected button and reset the selectedButton
@IBAction func actionTouchUpInside(sender: UIButton) {
if let selectedButton = self.selectedButton {
selectedButton.backgroundColor = UIColor.clear
}
sender.backgroundColor = UIColor.blue
selectedButton = sender
}
Upvotes: 0
Reputation: 285082
Simple solution without tags.
Declare a property currentButton
weak var currentButton : UIButton?
In changeView
reset the color of the currentButton
, set the color of the sender
and assign the sender
to currentButton
.
func changeView(_ sender: UIButton)
{
currentButton?.backgroundColor = .black
currentButton = sender
sender.backgroundColor = .red
}
Due to optional chaining the color of currentButton
will not be set if currentButton
is nil.
Upvotes: 0
Reputation: 3701
Since you're already using tags it shouldn't be a problem. The changeView
function should work like this:
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
}
}
Upvotes: 2