Brand new to Swift but am picking it up little by little. I have 2 objects that I want to control at the same time with UISwipeGestureRecognizer
. I have it working for one object but need to be able to swipe on the left side of the screen and the right side to control the 2 objects separately. I'm guessing I can implement a statement that if swipe is less than this position control this object else control this one just not sure how to implement. This is what I'm using to control the one object.
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)
}
And how do you intend the user to reflect which of the three gestures (up, left, and right) is for which object? Are you starting the gesture on top of the object? If that's the case, there are a couple of approaches.
The most logical approach, in my opinion, is to create a separate set of gestures for each object, and then in the gesture recognizer, you can look at gesture.view
to identify which one resulted in the gesture recognizer's selector to be called. For example:
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)
With a handleDownSwipe
like so:
func handleDownSwipe(gesture: UISwipeGestureRecognizer) {
if gesture.view == leftObject {
println("swiped left one")
} else if gesture.view == rightObject {
println("swiped right one")
}
}
Or, if the handling of the gestures for the two different objects were sufficiently different, you might just give them completely separate gesture handlers. It's just a question of how much common code there is in these two gesture handlers.
Alternatively, you could put the gesture recognizer on the superview that contains these two view objects:
let downSwipe = UISwipeGestureRecognizer(target: self, action: Selector("handleDownSwipe:"))
downSwipe.direction = .Down
view.addGestureRecognizer(downSwipe)
And then you could have the gesture recognizer look at the width of the view and compare that to the 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")
}
}