Marmelador
Marmelador

Reputation: 1017

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.

Upvotes: 3

Views: 2535

Answers (2)

abdullahselek
abdullahselek

Reputation: 8433

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

Upvotes: 7

RajeshKumar R
RajeshKumar R

Reputation: 15748

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
    }

Upvotes: 1

Related Questions