Search code examples
iosiphoneswiftuiviewuitouch

Getting the number of fingers touching a UIView


I want to change the color of a UIView based on the number of touches currently on it. I have managed to create this with a single touch:

class colorChangerViewClass: UIView {

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        setColor(color: .blue)
        print("touchesBegan")
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        setColor(color: .green)
        print("touchesEnded")
    }


    func setColor(color: UIColor) {
    self.backgroundColor = color
    }
}

But I am struggling with implementing multitouch. I feel like I'm not understanding something here.

Does UIView have a property to check how many fingers are currently touching it?

I could check that each time a new touchesBegan or touchesEnded occurs.


Solution

  • First enable multi touch on your subclass

    self.isMultipleTouchEnabled = true
    

    Then inside your touch event functions you can get all touches with event from your UIView class.

    let touchCount = event?.touches(for: self)?.count