Search code examples
iosswiftuitouch

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


My iPad app needs to be able to completely dismiss specific touches i.e. those that come from a finger or stylus and not from, say, the palm of your hand. The view has multi-touch enabled so that I analyse each touch separately.

I can currently differentiate between these touches using the majorRadius attribute but I'm not sure how I might be able to dismiss the larger touches i.e. those greater than my decided threshold.

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
        }
    }
}

Solution

  • If you only want to detect certain types of touches, here's a possible solution:

    Option 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")
        }
    }
    

    Option 2

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

    You can read more touch types here.