Controller-Klasse
Code: Select all
class ViewController: UIViewController {
var button: SomeButtonWithImage = {
let button = SomeButtonWithImage()
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
button = SomeButtonWithImage()
button.normalImage = "mute"
button.selectedImage = "unmute"
button.tag = index
button.widthAnchor.constraint(equalToConstant: controlButtonsHeight).isActive = true
button.heightAnchor.constraint(equalToConstant: controlButtonsHeight).isActive = true
button.addTarget(self, action: #selector(self.rightButtonAction), for: .touchUpInside)
rightStackView.addArrangedSubview(button)
}
}
Code: Select all
class SomeButtonWithImage: UIButton {
var buttonSelectedScale: CGFloat = 0.9
var buttonScaleDownDuration: TimeInterval = 0.15
var buttonScaleUpDuration: TimeInterval = 0.25
public var normalImage: String = ""
public var selectedImage: String = ""
override var isHighlighted: Bool {
didSet { if oldValue == false && isHighlighted { selected() }
else if oldValue == true && !isHighlighted { deselected() }
}
}
override init(frame: CGRect) {
super.init(frame: frame)
configuration = .plain()
configuration?.baseBackgroundColor = .clear
configurationUpdateHandler = { button in
switch button.state {
case .normal: button.configuration?.image = UIImage(named: self.normalImage)
case .selected: button.configuration?.image = UIImage(named: self.selectedImage)
default: break
}
}
}
required init?(coder: NSCoder) { fatalError("error") }
func selected() { animateScale(to: buttonSelectedScale, duration: buttonScaleDownDuration) }
func deselected() { animateScale(to: 1, duration: buttonScaleUpDuration); isSelected.toggle() }
private func animateScale(to scale: CGFloat, duration: TimeInterval) {
UIView.animate( withDuration: duration, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: [], animations: {
self.transform = .init(scaleX: scale, y: scale)
}, completion: nil)
}
}
Warum verwende ich ConfigurationHandler anstelle von setImage(UIImage?, for: UIControlState)? Wenn ich beim Klicken setImage verwende, wird das Bild mit einem grauen Hintergrund abgedeckt. Ich habe „adjustsImageWhenHighlighted = false“ verwendet, um das Problem zu lösen. Dies ist jedoch veraltet. Deshalb habe ich angefangen, die Konfiguration zu verwenden. Ich weiß, dass es mit dem Status „veraltet“ immer noch funktioniert. Aber ich habe Warnungen. Und ich wollte einen anderen Weg finden, das war die Konfiguration.