ios - Swift 设置子类 UIButton ButtonType

标签 ios swift uibutton swift4

我有一个 UIButton 的简单子(monad)类

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) 是一个方便的初始化器,我不确定如何实现它一个子类。

最佳答案

仍然不确定是否可以在子类中复制 .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...
}

关于ios - Swift 设置子类 UIButton ButtonType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59699138/

相关文章:

ios - UIButton 定义中的“隐藏实例变量”警告

ios - RESTful UIButton 操作的用户体验

ios - 开机时联系人的授权状态未更改

swift - 使用什么数据文件可以轻松导入到带有 Swift 的 iOS 应用程序中?

使用 self 进行 Swift 惰性实例化

ios - 将字符串转换为 plist - swift

ios - 如何获得黑色光泽的 UIButton 外观?

ios - Swift - 如何确保标签跟随 slider 的缩略图?

objective-c - 我如何查看哪些方法正在减慢我的 UIViewController 的显示速度?

ios - 代码 4 : some button titles not visible in iOS simulation