获取触摸UIView的手指数量

3

我希望根据当前触控的次数改变UIView的颜色。我已经成功地创建了单点触控的情况:

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

但是我在实现多点触控时遇到了困难。我感觉自己对此不够理解。

UIView是否有属性可以检查当前有几个手指在触摸它?

我可以在每次发生新的touchesBegan或touchesEnded时进行检查。

2个回答

7

首先在您的子类上启用多点触控

self.isMultipleTouchEnabled = true

那么在你的触摸事件函数中,你可以使用来自UIView类的事件获取所有触摸。
let touchCount = event?.touches(for: self)?.count

event?.touches(for: self)?.count 可能不总是有效,event?.allTouches?.counttouchesBegan 方法中也可能有帮助。 - kevinzhow

1
请确保 UIViewisMultipleTouchEnabled = true,默认值为 false
然后更改 touchesBegan 方法。
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        setColor(color: .blue)
        let touchCount = event?.touches(for: self)?.count
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接