класс контроллера
Код: Выделить всё
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)
}
}
Код: Выделить всё
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)
}
}
Почему я использую ConfigurationHandler вместо setImage(UIImage?, for: UIControlState)? Если я использую setImage при нажатии, изображение будет покрыто серым фоном. Я использовал это, регулируетImageWhenHighlighted = false, чтобы решить проблему. Но это устарело. Вот почему я начал использовать конфигурацию. Я знаю, что со статусом «устарело» он все еще работает. Но у меня есть предупреждения. И я хотел найти другой способ, такая была конфигурация.
Подробнее здесь: https://stackoverflow.com/questions/793 ... of-the-fin
Мобильная версия