【问题标题】:Value of type 'Set<UITouch>' has no member 'allObjects''Set<UITouch>' 类型的值没有成员 'allObjects'
【发布时间】:2016-10-02 20:27:40
【问题描述】:

嘿,在尝试跟踪多次触摸时,我收到了这个错误。而且我知道为什么我会因为 touchesbegin 函数顶部的 Set 而得到错误。但我必须将我的 Set 保留在 overrideBegin 中。那么我将如何解决此错误并在不更改原始覆盖值的情况下使此代码无错误。

代码:

  override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {


    var touchesArray = touches.allObjects()
    var nNumTouches = touchesArray.count
    var touch: UITouch!
    var ptTouch = CGPoint.zero
    for nTouch in 0..<nNumTouches {
        touch = touchesArray[nTouch]
        ptTouch = touch.locationInView(self.view)
        //I need it to print the location of each individual touch like finger 1 or finger 2 is in this location
    }

  }

【问题讨论】:

  • 应该不需要将集合转换为数组,可以遍历集合:for touch in touches { ... }

标签: ios swift xcode uitouch


【解决方案1】:

这是 Swift 的 Set,而不是 NSSet。试试:

let touchesArray = Array(touches)

但我发现这里不需要进行这种转换,因为您可以迭代集合。只试试这个:

for touch in touches {
    let point = touch.location(in: self.view)
    print("x: \(point.x), y: \(point.y)")
}

【讨论】:

  • 效果很好!当它允许我时,我会标记为答案。另外,如果我想打印每次触摸的位置,这肯定很容易。那我该怎么做呢?这会很有帮助@Kubba
  • print(String(format: "x=%.2f y=%.2f", ptTouch.x, ptTouch.y)) 这项工作用于跟踪一次触摸
【解决方案2】:

您可以在 touches 上使用 .count 而无需将其转换为数组。但没有必要,因为您可以遍历触摸集。

为了能够注册多个触摸,您需要将此行添加到您的 viewDidLoad() 方法中:view.multipleTouchEnabled = true

并像这样修改touchesBegan

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    for (index,touch) in touches.enumerate() {
        let ptTouch = touch.locationInView(self.view)
        print("Finger \(index+1): x=\(pTouch.x) , y=\(pTouch.y)")
    }

}

【讨论】:

  • 好的,我正在尝试跟踪多次触摸,因此我基本上可以不断运行一行代码来打印触摸 2 / 手指 2 的位置。但我不知道如何打印
  • @Hunter 你的意思是当你用两根手指敲击时要打印两根手指的位置?
  • 是的,这正是我想要做的,但基本上我希望 touch 1 有自己的位置,我希望 touch 2 有自己的位置。所以基本上在 touchesdidMove 中,我可以跟踪触摸 1 的位置(如果它移动),我可以单独跟踪触摸 2 的移动位置。通过简单地打印触摸是否移动,给我仍然在屏幕上的触摸 1 的位置,并给我仍然在屏幕上拖动的位置触摸 2
  • 好的 差不多了 我基本上需要说 let finger1 = index[1] 基本上说 let finger1 = touch number 1 或让它等于触摸屏幕的第一根手指 & let finger2 = touch 2 或触摸屏幕的第二根手指
  • @Hunter 如果您需要在 touchesMoved 方法中单独跟踪多个手指的位置,那么我建议您使用当前代码为 touchesBegan 和 @987654329 提出另一个问题@。因为它超出了这个问题的范围。我很乐意看看。
【解决方案3】:

为什么不做这样的事情?你的东西循环需要计数器吗?

let touchesArray = touches
var ptTouch: CGPoint?
for touch in touchesArray {
    ptTouch = touch.locationInView(self.view)

    print(ptTouch)
}

【讨论】:

  • 好的,我会尝试,但我真的想打印第一次触摸的位置,然后就像我想要的那样。打印 2,3 或 4 触摸的位置。你知道喜欢跟踪那里的位置。所以基本上,如果可以告诉我如何简单地打印触摸 2/手指 2 的位置,然后将错误标记为答案,这将有很大帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-10
  • 1970-01-01
  • 1970-01-01
  • 2023-04-07
  • 2016-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多