Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITapGestureRecognizer interferes with UISlider

I got a gesture related issue, somewhat similar to: gesture-problem-uiswipegesturerecognizer-uislider

But I code in swift and so I need a solution in swift.

What happens in my project is this: I have a ViewController on which a tap on the screen by the user, will perform a segue. But I have a UISlider on this viewcontroller, and when a user 'releases' the slider it is sometimes (why sometimes and not always, confuses me) recognized as a tap on the screen.

So I understand I have to prevent that the gesture recognizer 'sees/recognizes' touches on the UIslider.

But how do I prevent this? (in swift 2.0, using Xcode7. but I also understand it if u use earlier swift coding in an answer) I am fairly new to coding in swift. I hope someone can help!

Here is the code in the viewcontroller:

// The slider 
@IBOutlet weak var sliderValue: UISlider!

@IBAction func sliderValueChanged(sender: UISlider) {
// Do stuff
}

// UITapGestureRecognizer
override func viewDidLoad() {
    super.viewDidLoad()

let touch = UITapGestureRecognizer(target: self, action: "touched:")
        self.view.addGestureRecognizer(touch)
}

// Perform Segue
func touched (_: UIGestureRecognizer) {

    //Segue to another viewcontroller
    performSegueWithIdentifier("nice", sender: self)

}

(EDIT:) I updated my code with information I have found here on stackoverflow. I have added UIGestureRecognizerDelegate:

    class LampOn: UIViewController, UIGestureRecognizerDelegate {...}

And I have added shouldReceiveTouch:

func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {

    gestureRecognizer.delegate = self
    if (touch.view == sliderValue){
        print("touching slider")
        return false
    }
    else{
        print("touching elsewhere")
        return true
    }

}

But the 'shouldReceiveTouch` func never gets called from the console. So what am I missing? Did I set up the delegate correctly?

like image 517
codeDude Avatar asked May 25 '26 09:05

codeDude


1 Answers

The "shouldReceiveTouch" function is never called because you set the delegate inside the "shouldReceiveTouch" function. The delegate needs to be set to self BEFORE the function can be called.

What you need to do is to set the delegate inside the viewDidLoad() and everything should be fine.

override func viewDidLoad() {
  super.viewDidLoad()

  let touch = UITapGestureRecognizer(target: self, action: "touched:")
    self.view.addGestureRecognizer(touch)
    touch.delegate = self
}
like image 176
Chan Jing Hong Avatar answered May 27 '26 23:05

Chan Jing Hong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!