3

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.

Marmelador
  • 947
  • 7
  • 27

2 Answers2

7

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
abdullahselek
  • 7,893
  • 3
  • 50
  • 40
  • `event?.touches(for: self)?.count` may not always working, `event?.allTouches?.count` can also be helpful in `touchesBegan` method. – kevinzhow Jan 08 '21 at 06:20
1

Make sure the UIView has isMultipleTouchEnabled = true, the default is false.

Then change the touchesBegan method

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        setColor(color: .blue)
        let touchCount = event?.touches(for: self)?.count
    }
RajeshKumar R
  • 15,445
  • 2
  • 38
  • 70