我可以为一个按钮设置背景色,但我不知道如何将背景色设置为UIControlState.Highlighted.有可能吗?还是我需要走setBackgroundImage路?

推荐答案

如果有人路过,如果这是你不止一次需要的东西,另一条路可能更容易走...我为UIButton写了一个简短的扩展,它工作得很好:

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相关问答推荐

绑定到可选值的非可选属性?'

Variadic泛型与Swift中的值和类型参数包

如何在自定义视图中读取修改符子元素?

使用`JSONSerialiser`时,省略通用可选项

如何从 RC 加载场景作为 ModelEntity 而不是普通实体?

如何让默认函数参数引用另一个函数参数?

如何为等待函数调用添加超时

使用列表的下一项更新相同的视图

如何在 RxSwift 中获取 controlEvent 类型?

如何自己快速编写 Hashable 协议

VStack SwiftUI 中的动态内容高度

AES 加密和解密

是否可以在 Swift 中创建通用闭包?

Swift中switch 盒的详尽条件

UICollectionView 自定义单元格在 Swift 中填充宽度

无法停止 AVPlayer

在 Swiftui 中是否有一种简单的方法可以通过捏合来放大图像?

Facebook SDK 4.0 IOS Swift 以编程方式注销用户

swift 中的@property/@synthesize 类似功能

如何快速从另一个视图控制器重新加载表格视图