ios - 按下时反转按钮颜色?

标签 ios swift uibutton

我正在尝试使用这种样式的按钮:

enter image description here

这是我目前所拥有的:

otherbuttons

但是,我不确定在像示例中的中间按钮那样按下时如何为按钮获取正确的颜色。我已经设法让图像的颜色变成白色,方法是:

button.setImage(UIImage("Image_White_Version"), for: .highlighted)

但我不知道如何用颜色填充按钮的其余部分。有人可以帮我吗?

最佳答案

您可以像这样为特定状态设置 UIButton 的背景图像:

let image = UIImage.imageWithColor(someColor, size: CGSize(width: 1.0, height: 1.0))
btn.setBackgroundImage(image, for: .highlighted)

这是一个从颜色创建图像的函数(放在 UIImage 的扩展中):

extension UIImage {
    class func imageWithColor(_ color: UIColor, size: CGSize) -> UIImage {
        let rect = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        context!.setFillColor(color.cgColor)
        context!.fill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
}

关于ios - 按下时反转按钮颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44163606/

相关文章:

swift - 闭包中的隐式返回导致错误

ios - Swift - UITableViewCell 类 contentView 以编程方式约束没有宽度

objective-c - exc_breakpoint 在调试中是什么意思?

ios - 创建一个与 NSJSONSerialization dataWithJSONObject 一起工作的对象 :options:error:

objective-c - Phonegap + Facebook 插件 : Ready Xcodeproj Package for iOs

objective-c - actionSheet clickedButtonAtIndex 在 objective-c 中不起作用?

arrays - swift 的 iOS。当我尝试改变按钮数组时程序崩溃

ios - 使用 Firebase 字典在 Swift 中填充数组

ios - TitleForHeaderInSection 显示不正确

swift - Xcode 6 中圆角矩形的问题