![](/img/trans.png)
[英]Swift: Custom UIButton Class in View Controller Touch Event Not Trigger?
[英]Custom UIButton class for button touch event
是否可以創建一個帶有觸摸事件動畫的自定義UIButton類,每次用戶觸摸按鈕時都會自動調用該動畫?
import UIKit
class AnimatedButton: UIButton {
@objc private func buttonClicked(sender: UIButton) {
UIView.animate(withDuration: 0.5,
delay: 1.0,
usingSpringWithDamping: 1.0,
initialSpringVelocity: 0.2,
options: .curveEaseOut,
animations: {
//do animation
sender.transform = CGAffineTransform(scaleX: 0.6, y: 0.6)
},
completion: nil)
}
}
所以我不想在其中必須調用button.buttonTouched()的ViewController中創建一個動作。 每當我在所有UIButton中使用此類時,這應該自動發生。
有可能做這樣的事情嗎?
雖然繼承UIButton
不是東西,我願意,你想實現與子類按鈕所處的動畫動作UIButton
可以通過重載實現sendAction(_ action: Selector, to target: Any?, for event: UIEvent?)
根據UIControl
類中的注釋( UIButton
繼承自UIControl
)
發送動作。 第一個方法被稱為事件,它是您可以觀察或覆蓋行為的一點
class MyButton : UIButton {
override func sendAction(_ action: Selector, to target: Any?, for event: UIEvent?) {
debugPrint("Am here")
//do all your animation stuff here
super.sendAction(action, to: target, for: event)
}
}
因此,每當點擊按鈕時,將執行動畫,然后將調用IBAction
。 希望這可以幫助
像這樣創建按鈕的自定義類
class CustomButton:UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
configeBtn()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configeBtn()
}
func configeBtn() {
self.addTarget(self, action: #selector(btnClicked(_:)), for: .touchUpInside)
}
@objc func btnClicked (_ sender:UIButton) {
// animate here
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.