Tuesday, March 12, 2019

Handling Swipe Gesture in Swift

I'm developing a pet project and i need to swipe the screen left or right to switch between subviews as shown in the image below.


1. Add the following lines to the ViewController's viewDidLoad() method


    let right = UISwipeGestureRecognizer()
    right.direction = .right
    right.addTarget(self, action: #selector(swipeGestureHandler(_:)))
    buttonsContainerView.addGestureRecognizer(right)
        
    let left = UISwipeGestureRecognizer()
    left.direction = .left
    left.addTarget(self, action: #selector(swipeGestureHandler(_:)))
    buttonsContainerView.addGestureRecognizer(left)
 

The swipe gesture recognizer was added for the container view of those buttons. The buttons will detect the finger movement and propagate the event to their parent view. The parent/container view will call the handler method, swipeGestureHandler(_:), for the swipe event.

2. Add the event handler method

    
    @objc public func swipeGestureHandler(_ gestureRecognizer:UISwipeGestureRecognizer) {
        if gestureRecognizer.state == .ended
            && gestureRecognizer.numberOfTouchesRequired == 1 {
            
            if gestureRecognizer.direction == .right {
                slideInAdvancedOperationsView()
            } else if gestureRecognizer.direction == .left {
                slideInBasicOperationsView()
            }
        }
    }
 

The handler method must be marked with @objc.


No comments:

Post a Comment