OGeek|极客世界-中国程序员成长平台

标题: ios - 调用 touchescancelled 而不是 touchesended [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 03:54
标题: ios - 调用 touchescancelled 而不是 touchesended

我试图在触摸时点亮一个 View ,并在触摸结束时取消它。这样做时,我注意到当我从 View 中抬起手指时, - (void)touchesEndedNSSet *)touches withEventUIEvent *)event 方法没有被调用,而是 - (void)touchesCancelledNSSet *)touches withEventUIEvent *)event 方法在 View 上被调用。这是正常的行为吗?我认为如果由于系统问题(如内存不足警告)而取消触摸,则会调用 touchesCancelled。我通过使用 touchesCancelled 完成了我的工作,但我想知道为什么它不能正确调用 touchesEnded。是bug吗?



Best Answer-推荐答案


这不是正常行为。抬起手指时,应该调用 touchesEnded。

当您的 View 在触摸期间被移除或发生系统事件(例如,当您的手指触摸屏幕时锁定手机)时,应该调用touchesCancelled

参见 touchesEnded 的文档和 touchesCancelled .

没有您的代码,就不可能知道发生了什么。但是,即使您设法按应有的方式调用了 touchEnded,您似乎也希望对这两种情况都做出响应。迅速:

class MyView: UIView {
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        stopGlow()
    }

    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
        stopGlow()
    }

    private func stopGlow() {
        //Your code here...
    }
}

关于ios - 调用 touchescancelled 而不是 touchesended,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10325776/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4