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
基础教程推荐
- 在视图控制器的宽度上水平均匀分布 UIButton 的最简单方法? 2022-01-01
- Firebase 云消息传递令牌未生成 2022-01-01
- 在 iOS 7 下 CCMenu 错位 2022-01-01
- 从 UIWebView 访问元数据 2022-01-01
- EditText 中的 setHintTextColor() 2022-01-01
- 更改 UITableView 部分标题的颜色 2022-01-01
- UINavigationItem 的持久 rightBarButtonItem 属性 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- Android - 如何在runOnUiThread 中将数据传递给Runnable? 2022-01-01
- UINavigationBar 隐藏按钮文本 2022-01-01