Reputation: 35
I want to change the borderColor and titleColor synchronized. but it didn't change the border color.
How can I make setTitleColor
func applied to the border Color?
func setColor(button: UIButton) {
button.setTitleColor(UIColor.fromRGB(95, 61, 196), for: .selected)
button.layer.borderColor = UIColor.fromRGB(95, 61, 196).cgColor
}
@objc func handleCleaningKinds(_ sender: UIButton) {
setColor(button: sender)
deselectAllButtons()
sender.isSelected = true
}
func deselectAllButtons() {
for subView in stackView.subviews{
if let button = subView as? UIButton {
button.isSelected = false
//button.layer.borderColor = UIColor.white.cgColor
}
}
}
Upvotes: 0
Views: 983
Reputation: 11939
borderColor
doesn't work with UIButton
selectedState
, So you need to handle that by himself based on your button's current state.
So write function like this to update state:
func updateSelectedState(_ isSelected: Bool) {
button.layer.borderWidth = isSelected ? 1 : 0 // If need to hide border on normal state
button.layer.borderColor = isSelected ? UIColor.fromRGB(95, 61, 196).cgColor : UIColor.white.cgColor // If need another color on normal state
button.isSelected = isSelected
}
Then your two functions should be like this:
@objc func handleCleaningKinds(_ sender: UIButton) {
deselectAllButtons()
updateSelectedState(sender)
}
func deselectAllButtons() {
for subView in stackView.subviews{
if let button = subView as? UIButton {
updateSelectedState(false)
}
}
}
Also setting color func setColor(button: UIButton)
should not be called each time when button clicked, so you can call this function at viewDidLoad
or any other function, where you create buttons.
Upvotes: 1
Reputation: 322
Have you tried adding these 2 lines?
button.layer.masksToBounds = false
button.clipsToBounds = true
Upvotes: 0
Reputation:
You can try to add:
button.layer.borderWidth = 1
This might do the trick.
Upvotes: 0