Swift 3.0:按下后更改按钮颜色 [英] Swift 3.0: Change a button color once pressed

查看:36
本文介绍了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()
        }
    }
}

这篇关于Swift 3.0:按下后更改按钮颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆