【问题标题】:Getting touch coordinates in Swift 1.2在 Swift 1.2 中获取触摸坐标
【发布时间】:2015-04-30 21:12:59
【问题描述】:

我正在尝试获取屏幕上触摸的坐标,但每次它都给我0、0。我只能在新版本的Swift中找到这个功能的基本帮助,并没有关于这个问题.我在这里做错了什么?

override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
        let touch = touches.first as! UITouch
        let location = touch.locationInView(self.view)
        NSLog("location: %d, %d", location.x, location.y)
}

谢谢!

【问题讨论】:

  • 坐标是CGFloats,必须用“%f”打印。编译器不显示警告吗?
  • 德普。谢谢,马丁,就是这样!没有警告。
  • 我知道问题已经得到解答。我只是想鼓励你使用 println 而不是 NSLog。 println 函数是打印值的 Swift 方法,它比 NSLog 更容易和重要,因为您不需要格式说明符。 println("位置\(位置)")

标签: ios swift uitouch cgpoint


【解决方案1】:

根据 swift 1.2

override func touchesEnded(touches: Set<NSObject>!, withEvent event: UIEvent!) {
    if let touch = touches.first as? UITouch {
        let location = touch.locationInView(self.view)
        println("Location: \(location)")
    }
}

按照 Swift 1.1

override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
        let touch = touches.anyObject() as? UITouch
        let location = touch?.locationInView(self.view)
        println("Location: \(location)")
    }

经过测试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-20
    • 1970-01-01
    相关资源
    最近更新 更多