Swift全新,但我一点一点地接受它。我想用UISwipeGestureRecognizer
同时控制2个对象。我有它为一个对象工作,但需要能够在屏幕左侧滑动,右侧分别控制2个对象。我猜我可以实现一个声明,即如果滑动小于此位置控制,则此对象控制此对象只是不确定如何实现。这就是我用来控制一个对象。
self.swipeRightGesture.addTarget(self, action: Selector("handleRightSwipe:"))
self.swipeRightGesture.direction = .Right
self.swipeRightGesture.numberOfTouchesRequired = 1
self.view?.addGestureRecognizer(self.swipeRightGesture)
func handleRightSwipe(sender: UIGestureRecognizer) {
if !self.isMoving && self.isMovingUp == true{
self.leftobjectmoveright()
self.isMoving = true
self.isMoving = false
self.isMovingUp = false
}
}
func leftobjectmoveright() {
self.leftobject.physicsBody?.velocity = CGVectorMake(75,0)
}
答案 0 :(得分:0)
您打算如何让用户反映三个手势中的哪一个(向上,向左和向右)是哪个对象?你是在对象上面开始做手势吗?如果是这种情况,有几种方法。
在我看来,最合乎逻辑的方法是为每个对象创建一组单独的手势,然后在手势识别器中,您可以查看gesture.view
以确定哪一个导致手势识别器&# 39;要调用的选择器。例如:
let leftObjectDownSwipe = UISwipeGestureRecognizer(target: self, action: Selector("handleDownSwipe:"))
leftObjectDownSwipe.direction = .Down
leftObject?.addGestureRecognizer(leftObjectDownSwipe)
let rightObjectDownSwipe = UISwipeGestureRecognizer(target: self, action: Selector("handleDownSwipe:"))
rightObjectDownSwipe.direction = .Down
rightObject?.addGestureRecognizer(rightObjectDownSwipe)
如此handleDownSwipe
:
func handleDownSwipe(gesture: UISwipeGestureRecognizer) {
if gesture.view == leftObject {
println("swiped left one")
} else if gesture.view == rightObject {
println("swiped right one")
}
}
或者,如果两个不同对象的手势处理完全不同,您可能只是给它们完全独立的手势处理程序。这只是这两个手势处理程序中常见代码的问题。
或者,您可以将手势识别器放在包含这两个视图对象的超级视图上:
let downSwipe = UISwipeGestureRecognizer(target: self, action: Selector("handleDownSwipe:"))
downSwipe.direction = .Down
view.addGestureRecognizer(downSwipe)
然后你可以让手势识别器查看视图的宽度并将其与locationInView
进行比较:
func handleDownSwipe(gesture: UISwipeGestureRecognizer) {
let location = gesture.locationInView(gesture.view)
if location.x < (gesture.view!.frame.size.width / 2.0) {
println("swiped left side")
} else {
println("swiped right side")
}
}