Search code examples
swiftswipeviewcontrolleruiswipegesturerecognizer

How to reload the same viewcontroller with passed data using UISwipeGestureRecognizer


Sometimes it's difficult to come up with an accurate title for a question... but here goes:

I have a viewcontroller that I want to re-load with new data using UISwipeGestureRecognizer, I want to basically say "if UISwipeGestureRecognizer direction is up, x = x + 1 (I would also have a x = x - 1 for a down swipe). There are images that are dependent on passed integer that would automatically load also. Ideally, it would appear as if the swipe animated to a new page, but really it would be the same viewcontroller with different data.

It's difficult to ask this question in a coherent way, but I hope someone can get the gist of what I'm trying to do. If not, apologies. Thanks!


Solution

  • Add two Swipe Gesture Recognizers to your main view, one to detect the swipe up, and the other the swipe down, like this:

    class ViewController: UIViewController {
    
        // Your gesture recognizers:
        var swipeUpGestureRecognizer = UISwipeGestureRecognizer()
        var swipeDownGestureRecognizer = UISwipeGestureRecognizer()
    
        // Your x variable:
        var x = 0
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // Setup your gesture recognizers:
            swipeUpGestureRecognizer.direction = .up
            swipeUpGestureRecognizer.addTarget(self, action: #selector(swipeUpAction))
    
            swipeDownGestureRecognizer.direction = .down
            swipeDownGestureRecognizer.addTarget(self, action: #selector(swipeDownAction))
    
            // Inserting the gesture recognizers into the main view:
            self.view?.addGestureRecognizer(swipeUpGestureRecognizer)
            self.view?.addGestureRecognizer(swipeDownGestureRecognizer)
    
        }
    
        // Methods:
        func swipeUpAction() {
            // Update your data here!
            x = x + 1
        }
    
        func swipeDownAction() {
            // Update your data here!
            x = x - 1
        }
    
    }
    

    This should work just fine! Good luck!