您可以按如下方式以编程方式添加手势识别器
var touch = UITapGestureRecognizer(target:self, action:"action")
scrollView.addGestureRecognizer(touch)
但是,此手势识别器不适用于您。 UITapGestureRecognizer 只会在点击时返回,而不是点击并按住,并且 UILongPressGestureRecognizer 不会提供有关位置的信息,因此您想使用 UIPanGestureRecognizer。它不断地告诉您触摸移动了多远。
var touch = UIPanGestureRecognizer(target:self, action:"handlePan")
scrollView.addGestureRecognizer(touch)
@IBAction func handlePan(recognizer:UIPanGestureRecognizer) {
let translation = recognizer.translationInView(self.view)
recognizer.setTranslation(CGPointZero, inView: self.view)
}
您可以使用常量“平移”来移动对象,它表示人滑动手指的距离。使用它加上你的鸟的位置将鸟移动到一个新的点。调用此函数后,您必须将翻译重置为零。
编辑:根据你的游戏格式,这段代码应该是最好的方法。
所以,总而言之,找到手指位置的代码应该如下。
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
for touch: AnyObject in touches {
let location = touch.locationInView(yourScrollView)
}
}
@IBAction func handlePan(recognizer:UIPanGestureRecognizer) {
let translation = recognizer.translationInView(self.view)
var currentLocation : CGPoint = CGPointMake(location.x+translation.x, location.y+translation.y)
recognizer.setTranslation(CGPointZero, inView: self.view)
}
currentLocation 是一个包含当前触摸位置的 CGPoint,即手指滑动到的位置。由于我不知道您是如何创建要避免的视图,因此您必须使用 currentLocation 的 y 坐标来确定要在该 y 处避免的视图的 x 边界,并使用 比较器来确定如果触摸的 x 边界在其中任何一个视图内。
注意:您必须声明位置,以便可以在 handlePan 中访问它
var location : CGPoint = CGPointZero