简体   繁体   English

获取触摸UIView的手指数

[英]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. 我想根据当前触摸的次数更改UIView的颜色。 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? UIView是否有一个属性可以检查当前有多少手指在触摸它?

I could check that each time a new touchesBegan or touchesEnded occurs. 我可以检查是否每次发生新的touchesBegan或touchesEnded。

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. 然后,在您的触摸事件函数中,您可以从UIView类中获取事件的所有触摸。

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

Make sure the UIView has isMultipleTouchEnabled = true , the default is false . 确保UIView具有isMultipleTouchEnabled = true ,默认值为false

Then change the touchesBegan method 然后更改touchesBegan方法

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        setColor(color: .blue)
        let touchCount = event?.touches(for: self)?.count
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM