【问题标题】:Swift Setting subclass UIButton ButtonTypeSwift 设置子类 UIButton ButtonType
【发布时间】:2020-01-11 22:19:11
【问题描述】:

我有一个简单的 UIButton 子类

class IconButton: UIButton {

    init(type: FontAwesomeStyle, icon: FontAwesome, color: UIColor = .black, size: CGFloat = 20) {
        super.init(frame: CGRect.zero)

        let iconAsText = String.fontAwesomeIcon(name: icon)
        let iconText = NSMutableAttributedString(string: iconAsText, attributes: [
            NSAttributedString.Key.font: UIFont.fontAwesome(ofSize: size, style: type)
        ])

        setAttributedTitle(iconText, for: .normal)
        setTitleColor(color, for: .normal)

    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

我遇到的问题是我希望按钮具有系统按钮所具有的行为。特别是当您按住按钮时,它会改变颜色。

let button = UIButton(type: .system)

由于 buttonType 是 UIButton 的仅获取属性,而 UIButton.init(type: UIButton.ButtonType) 是便利初始化器,我不知道如何实现这个子类。

【问题讨论】:

    标签: ios swift uibutton swift4


    【解决方案1】:

    仍然不确定是否可以在子类中复制 .system 按钮类型,但获得我想要的行为的解决方案如下:

    class IconButton: UIButton {
    
        override var isHighlighted: Bool {
            willSet(newVal) {
               if newVal != isHighlighted {
                   // newVal is true when the button is being held down
    
               }
            }
        }
    
        // Rest of class...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-23
      • 2011-11-30
      • 1970-01-01
      • 2012-05-03
      • 2010-12-31
      • 1970-01-01
      相关资源
      最近更新 更多