UITapGestureRecognizer to switch between two UIViews in iOS Swift

 

This tutorial has been updated for X code 7.3 & swift 2.2

Even with plus size iPhone you have limited screen size available to display information. You can hide similar type of information in one view. And switch between two views by using uitapgesturerecognizer & uilongpressgesturerecognizer.

  1. First lets set up the x code project as usual. Create new single view application X code project. Set project name to tap gesture demo and save it on your desktop.

new x code project

 

2. Go to main storyboard and select view controller. Set its size iPhone 4-inch in attribute section.

 

size iPhone 4 inch

3. Drag UIView to view controller & set its dimension as follows

set view width & height

 

4. Drag another uiview & make it subview of previous view. Set its dimension as follows

set inner view height & width

 

5. Set its color to purple

set view color to purple

 

6. Drag another uiview & make it just like previous view except set its color to green

add another view & set green color

 

7. You should have following hierarchy in views

view hierarchy

8. Now connect tap gesture to view containing purple & green view

add tap gesture recognizer

9. Connect purple view to swift file

purple view as outlet to swift file

 

10. Connect green view to swift file

green view as outlet to swift file

 

11. Connect tap gesture recognizer to swift file

tap gesture to swift file

 

12. Create a bool just below view outlets

var isPurpleViewShowing = false

13. Add following code in tap gesture recognizer action

@IBAction func tappedToChangeView(sender: UITapGestureRecognizer) {

    if isPurpleViewShowing {
        UIView.transitionFromView(greenView, toView: purpleView, duration: 1.0, options: [UIViewAnimationOptions.TransitionFlipFromLeft, UIViewAnimationOptions.ShowHideTransitionViews] , completion: nil)
    }
    else {
        UIView.transitionFromView(purpleView, toView: greenView, duration: 1.0, options: [UIViewAnimationOptions.TransitionFlipFromRight, UIViewAnimationOptions.ShowHideTransitionViews], completion: nil)
    }
    isPurpleViewShowing = !isPurpleViewShowing
}

14. Now build and run app in iPhone 5s And tap on the view

change view with tap
Download X code file
Sometimes users are clumsy and they will long press on view. Hence
Challenge : Switch between UIViews when long pressed on view.

change view with long press
Download Challenge Solution

Total 0 Votes
0

Tell us how can I improve this tutorial?

+ = Verify Human or Spambot ?