【问题标题】:Getting the number of fingers touching a UIView获取触摸 UIView 的手指数
【发布时间】:2017-04-18 14:00:33
【问题描述】:

我想根据当前的触摸次数来更改 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 发生时。

【问题讨论】:

    标签: ios iphone swift uiview uitouch


    【解决方案1】:

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

    self.isMultipleTouchEnabled = true
    

    然后在你的触摸事件函数中,你可以从你的 UIView 类中获取所有的触摸事件。

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

    【讨论】:

    • event?.touches(for: self)?.count 可能并不总是有效,event?.allTouches?.count 也可以在 touchesBegan 方法中有所帮助。
    【解决方案2】:

    确保UIViewisMultipleTouchEnabled = true,默认为false

    然后改touchesBegan方法

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多