自定义UIButton没有点击效果

  • 本文关键字:UIButton 自定义 ios swift
  • 更新时间 :
  • 英文 :


当我初始化UIButton时,我可以在它的init中提供它的类型。然而,我不能给它一个类型,如果我使用自定义按钮,因为buttonType属性是get-only,我不能把它放在init函数以及。

class Button: UIButton {
init(placeholder: String) {
super.init(frame: .zero)
setTitle(placeholder, for: .normal)
setTitleColor(.white, for: .normal)
backgroundColor =  colorLiteral(red: 0.3647058904, green: 0.06666667014, blue: 0.9686274529, alpha: 1).withAlphaComponent(0.5)
layer.cornerRadius = 5
setHeight(50)
titleLabel?.font = .boldSystemFont(ofSize: 20)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}

是的,你不能从子类的init方法中调用convenience init(type buttonType: UIButton.ButtonType)(因为子类必须调用父类的指定初始化器),但你可以实现以下方法来创建系统类型的按钮:

class Button: UIButton {
static func systemButton(placeholder: String) -> Button {
let button = Button(type: .system)
button.setTitle(placeholder, for: .normal)
// ...
return button
}
}

最新更新