如何让我的应用程序忽略特定触摸?

How can I tell my app to ignore a specific touch?

我的 iPad 应用需要能够完全消除特定触摸,即来自手指或手写笔的触摸,不是 来自手掌的触摸手。该视图启用了多点触控,因此我分别分析每个触摸。

我目前可以使用 majorRadius 属性区分这些触摸,但我不确定如何才能消除较大的触摸,即那些大于我决定的阈值的触摸。

let touchThreshold : CGFloat = 21.0

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {
        if touch.majorRadius > touchThreshold {
            //dismiss the touch(???)
        } else {
            //draw touch on screen
        }
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {
        if touch.majorRadius > touchThreshold {
            //dismiss the touch(???)
        } else {
            //draw touch on screen
        }
    }
}

你可以改用这个方法

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer 
       shouldReceiveTouch:(UITouch *)touch;

您可以在其中检查手势类型,例如手势识别器是否为 UITapGestureRecognizer 类型

您可以检查触摸主要半径是否在您的阈值限制内,如果在您的阈值内,则通过 true,否则通过 false。

   - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer 
                                       shouldReceiveTouch:(UITouch *)touch
         {
                 if touch.majorRadius > touchThreshold 
                  {
                      //dismiss the touch(???)
                     return No;
                  } 
                  else 
                  {
                       //draw touch on screen
                      return Yes;
                   }

UIGestureRecognizer

UITouch

您还可以使用大半径公差来确定大半径的精度

More on Major radius tolerance

如果您只想检测某些类型的触摸,这里有一个可能的解决方案:

选项 1

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    touches.forEach { touch in
        switch touch.type {
        case .direct, .pencil:
            handleTouch(for: touch.majorRadius)
        case .indirect:
            // don't do anything
            return
        }
    }
}

func handleTouch(for size: CGFloat) {
    switch size {
    case _ where size > touchThreshold:
        print("do something")
    default:
        print("do something else")
    }
}

选项 2

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    touches.filter{([=11=].type == .direct || [=11=].type == .pencil || [=11=].type == .stylus) && [=11=].majorRadius > touchThreshold}.forEach { touch in
        print("do something")
    }
}

您可以阅读更多触摸类型here