触地重复事件不起作用
Touch down repeat event does not works
我希望我的按钮在用户点击它两次时更改其背景图像。为此,我正在使用 touchDown 重复事件。但是它不起作用。
button.addTarget(self, action: #selector(clickedRepeatOnPlate), for: .touchDownRepeat)
这让您可以设置双击视图的手势。
let tap = UITapGestureRecognizer(target: self, action: #selector(doubleTapped))
tap.numberOfTapsRequired = 2
view.addGestureRecognizer(tap)
记住 UIButton 是 UIView
至于苹果的oficial documentation关于.touchDownRepeat
:
A repeated touch-down event in the control; for this event the value of the UITouch tapCount method is greater than one.
每次用户点击按钮超过一次时都会触发此事件,因此点击四次会触发事件三次。
要仅触发双击,您需要创建一个 UITapGesture
并在其 numberOfTapsRequired
上设置 2:
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(clickedRepeatOnPlate))
tapGesture.numberOfTapsRequired = 2
button.addGestureRecognizer(tapGesture)
编辑
如果需要获取发送按钮作为函数参数,可以如下操作:
func addDoubleTapEvent() {
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(clickedRepeatOnPlate(gesture:)))
tapGesture.numberOfTapsRequired = 2
button.addGestureRecognizer(tapGesture)
}
@objc func clickedRepeatOnPlate(gesture: UITapGestureRecognizer) {
guard let button = gesture.view as? UIButton else { return }
print(button.titleLabel?.text)
}
输出
Optional("button")
我希望我的按钮在用户点击它两次时更改其背景图像。为此,我正在使用 touchDown 重复事件。但是它不起作用。
button.addTarget(self, action: #selector(clickedRepeatOnPlate), for: .touchDownRepeat)
这让您可以设置双击视图的手势。
let tap = UITapGestureRecognizer(target: self, action: #selector(doubleTapped))
tap.numberOfTapsRequired = 2
view.addGestureRecognizer(tap)
记住 UIButton 是 UIView
至于苹果的oficial documentation关于.touchDownRepeat
:
A repeated touch-down event in the control; for this event the value of the UITouch tapCount method is greater than one.
每次用户点击按钮超过一次时都会触发此事件,因此点击四次会触发事件三次。
要仅触发双击,您需要创建一个 UITapGesture
并在其 numberOfTapsRequired
上设置 2:
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(clickedRepeatOnPlate))
tapGesture.numberOfTapsRequired = 2
button.addGestureRecognizer(tapGesture)
编辑
如果需要获取发送按钮作为函数参数,可以如下操作:
func addDoubleTapEvent() {
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(clickedRepeatOnPlate(gesture:)))
tapGesture.numberOfTapsRequired = 2
button.addGestureRecognizer(tapGesture)
}
@objc func clickedRepeatOnPlate(gesture: UITapGestureRecognizer) {
guard let button = gesture.view as? UIButton else { return }
print(button.titleLabel?.text)
}
输出
Optional("button")