I\'ve a UIButton
and I\'ve created an extension to add background color for different state.
I\'m using the following code:
To implement custom button illumination, you need: - Set in the storyboard the background color and alpha that you want to see, when button is pressed - At the time of initialization, set the background and alpha as a button that is not pressed -Implement three methods for the button (Touch Down / Touch Up Side / Touch Drag Outside) - In them, change the button illumination
Update Swift 4
extension UIButton {
func setBackgroundColor(color: UIColor, forState: UIControlState) {
UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)
UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.setBackgroundImage(colorImage, for: forState)
}
}
Event Button Action Show Touch On Highlight
The reason it does not work is that you have not set the correct state: you are missing the [ .highlighted, .selected ]
state, and so it falls back to plain .normal
.
When both isSelected
and isHighlighted
are true, UIKit looks explicitly for the state-combination of the two, and will not accept any of them individually.
The original code extended with the missing state (and updated to valid syntax in Swift 5):
self.donateButton.setBackgroundColor(.green, for: [ .highlighted, .selected ])
self.donateButton.setTitleColor(.white, for: [ .highlighted, .selected ])
When your UIButton
is selected. If you focus on the button, it will not highlight the button as state .Highlighted
. If it is not selected, it will highlight it as your will. For it regards you have background image in your button, it will use the default effect to highlight a image. If you want to change the state to .Selected
, you have to set the variable selected
of UIButton
to true.
I found the issue, UIButton
was set to System.I simply changed it to Custom, it started working as expected.
Swift 5, IOS 13+
extension UIButton {
func setBackgroundColor(_ color: UIColor, for forState: UIControl.State) {
UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)
UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.setBackgroundImage(colorImage, for: forState)
}
}