如何在Swift中设置UIButton背景色forState:UIControlState.Highlighted

我可以设置一个button的背景颜色,但我不知道如何设置UIControlState.Highlighted的背景颜色。 这甚至有可能吗? 或者我需要沿着setBackgroundImagepath?

如果任何人停下来,另一种方式可能会更容易,如果这是你需要不止一次…我为UIButton写了一个简短的扩展,它工作得很好:

 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) }} 

你可以像setBackgroundImage一样使用它:

 yourButton.setBackgroundColor(UIColor.whiteColor(), forState: UIControlState.Highlighted) 

语法更改为Swift 3及更高版本的 @winterized扩展

 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) }} 

下面将是一个方法去。 两个IBActions。 一个按下button时控制背景颜色,一个在发布时。

 import UIKit class ViewController: UIViewController { @IBOutlet weak var button: UIButton! @IBAction func buttonClicked(sender: AnyObject) { //Touch Up Inside action button.backgroundColor = UIColor.whiteColor() } @IBAction func buttonReleased(sender: AnyObject) { //Touch Down action button.backgroundColor = UIColor.blueColor() } override func viewDidLoad() { super.viewDidLoad() } } 

在添加句点后查看button的自动完成选项时,可以设置背景颜色,但不能指定状态。 您只能设置背景图像。 现在当然,如果你这样做,而不是使用上面显示的方法,你可以使用setbackgroundImageForState属性加载所需颜色的图像作为背景图像。

在这里输入图像说明

在这里输入图像说明

我们可以使用运行时属性来做同样的事吗?

 @IBInspectable var HighlightedBackground: Bool { get { return true } set { layer.backgroundColor = Common.sharedInstance.OrangeColor.CGColor print("highlighted state") } } 

Swift 4 这个解决scheme的版本:

 extension UIButton { func setBackgroundColor(_ color: UIColor, for state: 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() setBackgroundImage(colorImage, for: state) } }