我试图在Swift 4的UIView中触摸时获取各个点的坐标。我已经看过另一篇有关类似问题的文章,但是该代码仅允许注册第一次触摸。我将不胜感激。谢谢。
答案 0 :(得分:1)
因此,我也能够找到我的问题的答案:我在UIViewController中使用下面的代码在触摸不同位置时获得2d整数数组。感谢您的所有帮助。
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
}
}
答案 1 :(得分:0)
您可以在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)")
}
答案 2 :(得分:0)
此代码将为您每次触摸屏幕提供坐标。您可以通过将其打印出来或直接放入标签中进行测试。
@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)"
}
}