Niall Kehoe Niall Kehoe - 4 years ago 167
iOS Question

Limiting UISwipeGestureRecognizer Area

I'm using a number of

as selectors for a menu. Since I have more than one I need to have a limited area of swipe detection. This is the code I'm using:

var rightSwipe = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipe1"))

rightSwipe.direction = .right


I've tried adding it to a UIImageView but it won't detect touches.

Answer Source

isUserInteractionEnabled for UIImage and UILabel is false by default. Set it to true.

As I know, you can't limit gesture area. But you can check location of gesture and decide what to do with it.

For example:

func addGesture() {
    let rightGesture = UISwipeGestureRecognizer(target: self, action: #selector(someAction(sender:)))
    rightGesture.direction = .right

    let leftGesture = UISwipeGestureRecognizer(target: self, action: #selector(someAction(sender:)))
    leftGesture.direction = .right


func someAction(sender: UISwipeGestureRecognizer) {
    let location = sender.location(in: view)
    if location.x > view.frame.width / 2 && sender.direction == .right {
        // do something
    } else if location.x < view.frame.width / 2 && sender.direction == .left {
        // do something else
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download