Custom UIButton class for button touch event(用于按钮触摸事件的自定义 UIButton 类)
问题描述
是否可以创建一个自定义 UIButton 类,其中包含每次用户触摸按钮时都会自动调用的触摸事件动画?
Is it possible to create a custom UIButton class with an touch event animation which gets automatically invoked everytime the user touches the button?
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)
}
}
所以我不想在 ViewController 中创建必须调用 button.buttonTouched() 的操作.每次我在所有 UIButton 中使用此类时,都会自动发生这种情况.
So I don't want to create an action in a ViewController in which button.buttonTouched() must be invoked. This should happen automatically everytime I use this class in all UIButton.
有没有可能做这样的事情?
Is there any possibility to do something like that?
推荐答案
像这样创建按钮的自定义类
Create the button's custom class like this
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
}
}
这篇关于用于按钮触摸事件的自定义 UIButton 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:用于按钮触摸事件的自定义 UIButton 类


- 在 Iphone SDK 的导航栏上添加多个按钮 2022-01-01
- SetOnItemSelectedListener上的微调程序错误 2022-01-01
- GPS状态的广播接收器? 2022-01-01
- 如何在 iPhone 模拟器中重置 NSUserDefaults 数据? 2022-01-01
- Xcode 7.3 中带有 UILabel 的 UIStackView 2022-01-01
- 使用自动布局向 UIScrollView 添加动态大小的视图 2022-01-01
- 网上有没有好的 UIScrollView 教程? 2022-01-01
- UITextView 内容插图 2022-01-01
- 类似于 Mail.app 的 iPad 模态视图控制器? 2022-01-01
- URL编码Swift iOS 2022-01-01