UIButton touchDragEnter 和 touchDragExit 调用太频繁
UIButton touchDragEnter and touchDragExit called too often
如何避免快速触发 UIButtons .touchDragEnter 和 .touchDragExit 函数? ,但唯一的答案没有描述如何解决它。我试图在用户将手指放在按钮上时为按钮制作动画,并在他们的手指滑开时再次为它制作动画。有没有更好的方法来做到这一点?如果不是,当用户手指正好位于 .enter 和 .exit 状态之间时,我应该如何阻止我的动画代码多次触发?
您可以改为跟踪触摸点本身的位置,并确定触摸点何时移入和移出按钮
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let point = t.location(in: self)
// moving in to the button
if button.frame.contains(point) && !wasInButton {
// trigger animation
wasInButton = true
}
// moving out of the button
if !button.frame.contains(point) && wasInButton {
// trigger animation
wasInButton = false
}
}
}
wasInButton 可以是一个布尔变量,当按下按钮的框架时设置为 true:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let point = t.location(in: self)
if button.frame.contains(point) {
wasInButton = true
// trigger animation
} else {
wasInButton = false
}
}
这需要您子类化按钮的超级视图。由于您可能不想在点离开按钮框架时立即设置动画(因为用户的手指或拇指仍会覆盖按钮的大部分),因此您可以改为在封装按钮的较大框架中进行命中测试。
如何避免快速触发 UIButtons .touchDragEnter 和 .touchDragExit 函数?
您可以改为跟踪触摸点本身的位置,并确定触摸点何时移入和移出按钮
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let point = t.location(in: self)
// moving in to the button
if button.frame.contains(point) && !wasInButton {
// trigger animation
wasInButton = true
}
// moving out of the button
if !button.frame.contains(point) && wasInButton {
// trigger animation
wasInButton = false
}
}
}
wasInButton 可以是一个布尔变量,当按下按钮的框架时设置为 true:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let point = t.location(in: self)
if button.frame.contains(point) {
wasInButton = true
// trigger animation
} else {
wasInButton = false
}
}
这需要您子类化按钮的超级视图。由于您可能不想在点离开按钮框架时立即设置动画(因为用户的手指或拇指仍会覆盖按钮的大部分),因此您可以改为在封装按钮的较大框架中进行命中测试。