有没有一种方法可以在不使用选择器的情况下响应 UIButton 点击?
Is there a way to respond to UIButton tap without using selectors?
响应 UIButton 点击的标准方式是:
- 静态 link 方法和点击事件
IBAction
。
- 使用
UITapGestureRecognizer
,指定 target
和 action
(选择器)。
我希望事件处理程序是 swift block
/closure
,它们更灵活(没有特定 target/action),并且允许重新配置。
有没有办法在不跳过 target/action 的圈套的情况下做到这一点?
顺便说一句,我正在使用 Swift 3。
我读过这个问题,它使用了私有方法:
Gesture Recognizers and Blocks
您可以创建自己的按钮子类,将选择器语法包装在基于闭包的 API 周围。
class MyButton: UIButton {
var action: (() -> ())?
override init(frame: CGRect) {
super.init(frame: frame)
sharedInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
sharedInit()
}
private func sharedInit() {
addTarget(self, action: #selector(touchUpInside), for: .touchUpInside)
}
@objc private func touchUpInside() {
action?()
}
}
然后给按钮添加一个动作,设置关闭即可。
let button = MyButton()
button.action = {
print("hello")
}
响应 UIButton 点击的标准方式是:
- 静态 link 方法和点击事件
IBAction
。 - 使用
UITapGestureRecognizer
,指定target
和action
(选择器)。
我希望事件处理程序是 swift block
/closure
,它们更灵活(没有特定 target/action),并且允许重新配置。
有没有办法在不跳过 target/action 的圈套的情况下做到这一点?
顺便说一句,我正在使用 Swift 3。
我读过这个问题,它使用了私有方法: Gesture Recognizers and Blocks
您可以创建自己的按钮子类,将选择器语法包装在基于闭包的 API 周围。
class MyButton: UIButton {
var action: (() -> ())?
override init(frame: CGRect) {
super.init(frame: frame)
sharedInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
sharedInit()
}
private func sharedInit() {
addTarget(self, action: #selector(touchUpInside), for: .touchUpInside)
}
@objc private func touchUpInside() {
action?()
}
}
然后给按钮添加一个动作,设置关闭即可。
let button = MyButton()
button.action = {
print("hello")
}