简体   繁体   中英

iOS (Swift): Dimming UIButton when pressed

I have a UIButton subclass that is generated as follows:

class MoreOptionsButton: UIButton {

    override func draw(_ rect: CGRect) {

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

        let r = CGRect(x: rect.width * 0.5 - rect.width * 0.15 * 0.5, y: rect.height * 0.5 - rect.height * 0.15 * 0.5, width: rect.width * 0.15, height: rect.height * 0.15)
        var circlePath = UIBezierPath(ovalIn: r)
        UIColor.white.setFill()
        circlePath.fill()

        circlePath = UIBezierPath(ovalIn: r.offsetBy(dx: -rect.width / 4.0, dy: 0.0))
        UIColor.white.setFill()
        circlePath.fill()

        circlePath = UIBezierPath(ovalIn: r.offsetBy(dx: rect.width / 4.0, dy: 0.0))
        UIColor.white.setFill()
        circlePath.fill()

    }

}

and looks like this:

在此处输入图片说明

However, when I press down on this button in the simulator it does not automatically dim like a normal System type button would. How do I achieve this effect, please?

Add below code in your UIButton custom class:

override var isHighlighted: Bool {
    didSet {
        alpha = isHighlighted ? 0.4 : 1
    }
}

在此处输入图片说明

有两种按钮选择状态和未选择状态,您可以为这两种状态分配图像。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM