状态更改时更改按钮颜色

时间:2018-02-26 09:45:46

标签: ios swift xcode uibutton

enter image description here

我希望按钮在突出显示时具有白色背景和蓝色标题。我有一个UIButton的扩展来设置它的背景颜色。

extension UIButton {
    func setBackgroundColor(color: UIColor, forState: UIControlState) {
        UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
        UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)
        UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
        let colorImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        self.setBackgroundImage(colorImage, for: forState)
        self.clipsToBounds = true
    }

}

在下一个功能中,我设置了一个特定的按钮。

private func stylizingButton(button: UIButton){
        button.layer.borderWidth = 2
        button.layer.borderColor = textColor.cgColor
        button.layer.cornerRadius = 8
        button.setTitleColor(textColor, for: .normal)

        button.setTitleColor(backgroundColor, for: .highlighted)
        button.setBackgroundColor(color: .white, forState: .highlighted)

    }

当我将按钮的背景颜色更改为黑色时,结果是深蓝色。它就像屏幕背景颜色和按钮的颜色混合。

3 个答案:

答案 0 :(得分:2)

为您的按钮创建一个自定义类,并在下面的状态下处理您的颜色更改属性。

class MyButton: UIButton {
    fileprivate var titleColorNormal: UIColor = .white
    fileprivate var titleColorHighlighted: UIColor = .blue
    fileprivate var backgroundColorNormal: UIColor = .blue
    fileprivate var backgroundColorHighlighted: UIColor = .white
    override var isHighlighted: Bool {
        willSet(newValue){
            if newValue {
                self.setTitleColor(titleColorHighlighted, for: state)
                self.backgroundColor = backgroundColorHighlighted
            }else {
                self.setTitleColor(titleColorNormal, for: state)
                self.backgroundColor = backgroundColorNormal
            }
        }
    }
}

答案 1 :(得分:0)

要么为整个尺寸制作图像,要么使其可伸缩,这样就可以填满整个背景:

extension UIButton {

    func setBackgroundColor(color: UIColor, for state: UIControlState) {

        let rect = CGRect(origin: CGPoint(x: 0, y:0), size: CGSize(width: 1, height: 1))
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()!

        context.setFillColor(color.cgColor)
        context.fill(rect)

        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        let insets = UIEdgeInsetsMake(0, 0, 0, 0)
        let stretchable = image!.resizableImage(withCapInsets: insets, resizingMode: .tile)
        self.setBackgroundImage(stretchable, for: state)
    }

}

答案 2 :(得分:0)

我在突出显示状态下混合颜色时遇到了相同的问题,但不想创建自定义类。我发现您可以简单地将按钮类型从“系统”更改为“自定义”。然后,您可以使用功能按状态设置颜色。颜色将按定义显示。

You can change the button type in interface builder.