How do I set UIButton background color forState: UIControlState.Highlighted in Swift(如何在 Swift 中设置 UIButton 背景颜色 forState: UIControlState.Highlighted)
问题描述
我可以为按钮设置背景颜色,但我不知道如何为 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:
对于 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)
}
}
对于 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)
}
}
}
你像 setBackgroundImage
一样使用它:
yourButton.setBackgroundColor(color: UIColor.white, forState: UIControl.State.highlighted)
这篇关于如何在 Swift 中设置 UIButton 背景颜色 forState: UIControlState.Highlighted的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Swift 中设置 UIButton 背景颜色 forState: UIControlState.Highlighted


- 类似于 Mail.app 的 iPad 模态视图控制器? 2022-01-01
- 如何在 iPhone 模拟器中重置 NSUserDefaults 数据? 2022-01-01
- URL编码Swift iOS 2022-01-01
- UITextView 内容插图 2022-01-01
- 使用自动布局向 UIScrollView 添加动态大小的视图 2022-01-01
- 在 Iphone SDK 的导航栏上添加多个按钮 2022-01-01
- 网上有没有好的 UIScrollView 教程? 2022-01-01
- SetOnItemSelectedListener上的微调程序错误 2022-01-01
- GPS状态的广播接收器? 2022-01-01
- Xcode 7.3 中带有 UILabel 的 UIStackView 2022-01-01