I can set the background color for a button but I can't work out how to set the background color for UIControlState.Highlighted
. Is it even possible? or do I need to go down the setBackgroundImage
path?
Add a button on your storyboard, select it Go to it's attribute inspector and select 'Background' property to choose the color.
There are two ways to use your custom colors in Swift UI. Select your object in device preview. Choose “Color” under the attributes inspector. Your custom colors now show at the bottom of the list!
To add a screen background view by putting it at the bottom of the ZStack. Text("Hello, SwiftUI!") <1> Use ZStack so we can place a background view under the content view. <2> Use color view as background.
If anyone stops by, another way to go maybe more easily if it is something you need more than once... I wrote a short extension for UIButton, it works just fine:
for Swift 3
extension UIButton { func setBackgroundColor(color: UIColor, forState: UIControlState) { UIGraphicsBeginImageContext(CGSize(width: 1, height: 1)) CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), color.CGColor) CGContextFillRect(UIGraphicsGetCurrentContext(), CGRect(x: 0, y: 0, width: 1, height: 1)) let colorImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() self.setBackgroundImage(colorImage, forState: forState) } }
for Swift 4
extension UIButton { func setBackgroundColor(color: UIColor, forState: UIControl.State) { self.clipsToBounds = true // add this to maintain corner radius UIGraphicsBeginImageContext(CGSize(width: 1, height: 1)) if let context = UIGraphicsGetCurrentContext() { context.setFillColor(color.cgColor) context.fill(CGRect(x: 0, y: 0, width: 1, height: 1)) let colorImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() self.setBackgroundImage(colorImage, for: forState) } } }
You use it just like setBackgroundImage
:
yourButton.setBackgroundColor(color: UIColor.white, forState: UIControl.State.highlighted)
Syntax changes to @winterized extension for Swift 3+ syntax
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) }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With