如何突出显示没有文本或背景的自定义 UIButton?

How to highlight a custom UIButton that has no text or background?

我正在尝试制作自定义 UIButton,因为我想绘制自己的矢量按钮图标,而不是依赖于文本字符或位图图像。

所以...我试过了:

import UIKit

@IBDesignable
class CustomPlusButton: UIButton {

/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
    // Drawing code
}
*/


func myPlusSign() -> UIBezierPath {

    //vars to factor out later
    let G = bounds.width / 5

    let plusPath = UIBezierPath()


    let startPoint = CGPoint(x:2*G,y:G)

    plusPath.move(to: startPoint)
    plusPath.addLine(to: CGPoint(x:2*G,y:2*G))
    plusPath.addLine(to: CGPoint(x:G,y:2*G))
    plusPath.addLine(to: CGPoint(x:G,y:3*G))
    plusPath.addLine(to: CGPoint(x:2*G,y:3*G))
    plusPath.addLine(to: CGPoint(x:2*G,y:4*G))
    plusPath.addLine(to: CGPoint(x:3*G,y:4*G))
    plusPath.addLine(to: CGPoint(x:3*G,y:3*G))
    plusPath.addLine(to: CGPoint(x:4*G,y:3*G))
    plusPath.addLine(to: CGPoint(x:4*G,y:2*G))
    plusPath.addLine(to: CGPoint(x:3*G,y:2*G))
    plusPath.addLine(to: CGPoint(x:3*G,y:G))
    plusPath.addLine(to: startPoint)

    plusPath.close()

    plusPath.fill()

    return plusPath



}

override func draw(_ rect: CGRect) {

    let path = myPlusSign()

    path.stroke()

}
}

我将一个 Button 实例拖到情节提要中并将其类型更改为我的自定义 class。

在情节提要中,当我 运行 应用程序时,就矢量的外观以及它如何适合按钮而言,它看起来很棒 space,但它不会突出显示触摸普通按钮的方式。

据我了解,通常您会使用属性检查器的 "State config" 部分来控制突出显示时的行为,但它只允许控制文本颜色、阴影颜色、图像或背景。

我的自定义图标是 none 这些东西...那么我该如何引用它呢? draw(_ rect) 的输出指的是什么,我该如何突出显示它?

编辑:我也希望它像普通按钮一样淡化回正常状态,所以希望有某种方法可以 incorporate/reuse 普通按钮的突出显示行为而不完全覆盖它?

谢谢!

对于可能的解决方案,您可以在按钮的覆盖 isHighlighted.

didSet 中修改按钮的 alpha
override var isHighlighted: Bool {
    didSet {
        alpha = isHighlighted ? 0.7 : 1
    }
}