如何创建类似于.system类型的UIButton?

时间:2019-05-13 07:56:36

标签: ios swift uibutton

如何创建具有类似于UIButton但不指定UIButton(type: .system)类型的点击效果的.system

let btn = UIButton(frame: CGRect.zero)
// How to set the tap effect?

如何设置点击效果,使点击后文字闪烁?

3 个答案:

答案 0 :(得分:2)

您可以使用简单的UIButton子类并覆盖isHighlighted

class CustomButton: UIButton {

    override var isHighlighted: Bool {
        get { return super.isHighlighted }
        set {
            guard newValue != isHighlighted else { return }

            if newValue == true {
                titleLabel?.alpha = 0.25
            } else {
                UIView.animate(withDuration: 0.25) {
                    self.titleLabel?.alpha = 1
                }
                super.isHighlighted = newValue
            }

            super.isHighlighted = newValue
        }
    }

}

答案 1 :(得分:2)

您可以轻松地声明自己的自定义类,如下所示:

class CustomButton: UIButton {

override init(frame: CGRect) {
    super.init(frame: frame)

}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    self.setTitleColor(self.titleColor(for: .normal)?.withAlphaComponent(0.5), for: .highlighted)
} }

答案 2 :(得分:0)

您可以将按钮设置为系统类型,然后设置框架

let btn = UIButton(type: .system)
btn.frame = .zero