【问题标题】:Get various coordinates for touches in swift快速获取触摸的各种坐标
【发布时间】:2018-11-04 00:42:06
【问题描述】:

我试图在 swift 4 的 UIView 中触摸时获取各个点的坐标。我已经看到有关类似问题的另一篇文章,但该代码只允许注册第一次触摸。我会很感激一些帮助。谢谢。

【问题讨论】:

    标签: swift touchesbegan


    【解决方案1】:

    所以,我也能够找到我的问题的答案:我在 UIViewController 中使用下面的代码在不同位置触摸时获取整数的二维数组。感谢所有的帮助。

    var positionArray = Array(repeating: Array(repeating: 0, count: 2), count: 10)
        var counter = 0
        override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
            if let touch = touches.first {
                let position = touch.location(in: self.view)
                let locx = Int(position.x)
                let locy = Int(position.y)
                    positionArray[counter] = [locx, locy]
                    print(positionArray[counter])
                    counter = counter + 1
            }
        }
    

    【讨论】:

      【解决方案2】:

      此代码将为您提供每次触摸屏幕的坐标。您可以将其打印出来或直接贴在标签上进行测试。

      @IBOutlet weak var imageView: UIImageView!
      var coordinates = CGPoint.zero
      
          override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
              if let touch = touches.first{
              coordinates = touch.location(in: imageView)
              print(coordinates)
              textLabel.text = "\(coordinates)"
          }
      }
      

      【讨论】:

        【解决方案3】:

        您可以在 UIView 子类上实现 touchesMoved 回调来执行此操作。

        func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?)
        

        这个函数在触摸过程中被重复调用。

        大致思路如下:

        override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
            guard let touch = touches.first else {
                return
            }
        
            let location = touch.location(in: self)
            print("x = \(location.x), y = \(location.y)")
        }
        

        【讨论】:

        • 谢谢!当您停止触摸然后在另一个地方触摸时,这是否有效?
        • 是的。如果你停止触摸,那么你会得到一个 touchesEnded 回调(如果你已经实现了它)。然后当你触摸另一个地方时,你会得到一个 touchesBegan,然后是更多 touchesMoved。
        • 很抱歉以这种方式与您联系(我的评论与您在此处的输入无关)。我遇到了一个你在“分类”中投票的问题,你做出了错误的选择。请:仔细研究分类帮助,避免将不属于那里的项目放入编辑队列。我希望您将此视为改善投票的机会。我特指stackoverflow.com/review/triage/21317141。如果您对我有其他问题或反馈,请随时给我留言。如果你给我一个简短的提示,我会迅速删除这条评论。
        • 嗨,ncke。我给 Daniel 打分是因为解释更详细——而且我显然不知道如何使用 touchesEnded——,但它们似乎都有效。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-28
        • 2011-02-25
        • 1970-01-01
        • 2015-01-05
        • 2016-12-15
        相关资源
        最近更新 更多