Swift 3.0:按下后更改按钮颜色

问题描述:

我创建了一个圆形的绿色按钮.这是 CircularButton.swift,我在其中定义了颜色和形状,如下所示:

I've created a circular green button. Here is the CircularButton.swift where I've defined color and shape as below:

import UIKit

class CircularButton: UIButton {

@IBInspectable var fillColor: UIColor = UIColor.green

override func draw(_ rect: CGRect) {

    let path = UIBezierPath(ovalIn: rect)
    fillColor.setFill()
    path.fill()

    }
}

这是屏幕截图.

在按下的按钮上,我想将其颜色更改为红色.我已经定义了如下函数:

On the button pressed I would like to change its color to red. I've defined the function as below:

@IBAction func circularButtonPressed(_ sender: CircularButton) {
    sender.fillColor = UIColor.red
    sender.draw(CGRect(x: 0, y: 0, width: sender.frame.width,
                       height: sender.frame.height))
}

知道为什么颜色没有变成红色吗?

Any idea why the color is not changed to red?

注意:如果我添加以下行:

sender.backgroundColor = UIColor.white

在上述函数中,按钮颜色变为红色.

in the above function, the button color changes to red.

感谢您的帮助.

您不应直接从代码内部调用 draw(_:).你只需要告诉iOS控件需要重绘.

You should not call draw(_:) from inside your code directly. You just need to tell iOS that the control needs to be redrawn.

删除调用draw(_:)的行:

@IBAction func circularButtonPressed(_ sender: CircularButton) {
    sender.fillColor = UIColor.red
}

并将观察者添加到 fillColor 属性:

And add observer to the fillColor property:

@IBInspectable var fillColor: UIColor = UIColor.green {
    didSet(oldColor) {
        if fillColor != oldColor {
            self.setNeedsDisplay()
        }
    }
}