本文介绍了如何在状态中设置UIButton背景颜色:UIControlState.Highlighted在Swift中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以设置按钮的背景颜色,但我无法弄清楚如何设置 UIControlState.Highlighted
的背景颜色。它甚至可能吗?或者我需要沿着 setBackgroundImage
路径?
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?
推荐答案
如果任何人都会停下来,另一种方式可能更容易,如果它是你需要不止一次...我为UIButton写了一个简短的扩展,它的工作正常:
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:
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)
这篇关于如何在状态中设置UIButton背景颜色:UIControlState.Highlighted在Swift中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!