Reputation: 435
I have a simple subclass of 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")
}
}
The problem I am having is that I would like the button to have the behavior that system buttons have. Specifically when you press and hold the button, it changes color.
let button = UIButton(type: .system)
Since buttonType
is a get only property of UIButton and UIButton.init(type: UIButton.ButtonType)
is a convenience initailizer, I am not sure how to implement this a subclass.
Upvotes: 1
Views: 335
Reputation: 435
Still not sure if its possible to replicate the .system
button type in a subclass, but the solution for getting the behavior I wanted was the following:
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...
}
Upvotes: 1