【发布时间】:2018-11-04 00:42:06
【问题描述】:
我试图在 swift 4 的 UIView 中触摸时获取各个点的坐标。我已经看到有关类似问题的另一篇文章,但该代码只允许注册第一次触摸。我会很感激一些帮助。谢谢。
【问题讨论】:
标签: swift touchesbegan
我试图在 swift 4 的 UIView 中触摸时获取各个点的坐标。我已经看到有关类似问题的另一篇文章,但该代码只允许注册第一次触摸。我会很感激一些帮助。谢谢。
【问题讨论】:
标签: swift touchesbegan
所以,我也能够找到我的问题的答案:我在 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
}
}
【讨论】:
此代码将为您提供每次触摸屏幕的坐标。您可以将其打印出来或直接贴在标签上进行测试。
@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)"
}
}
【讨论】:
您可以在 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)")
}
【讨论】: