How to Dismiss viewcontroller?

While development you may face scenario in which you have to navigation to previous screen. We can achieve this by using different technics.

Scenario :  Suppose View have two screen ViewController and DetailViewController and we are navigating from ViewController to DetailViewController by pressing “+” button and on “Cancel” button click we have to navigate back to ViewController.

(To embed navigation controller to viewcontroller go to Editor menu -> Embed In -> Navigation Controller)


1. Basic Way

on Cancel button click dismiss the view

 @IBAction func btnCancel(_ sender: AnyObject) {
     self.dismiss(animated: true, completion: {})

But what if we have 100 of such screen? to write same code 100 times in not good coding practice. To avoid this we can create extension of UIViewController

2. Using Extension

Create extension of UIViewController give this file name as UIViewController+DismissViewController 

import Foundation
import UIKit
extension UIViewController{
    func dismissViewController(){
        self.dismiss(animated: true, completion: {})

Now you can use this function in every ViewController.

you just have to call method dismissViewController from extension

 @IBAction func btnCancel(_ sender: AnyObject) {

3. Using Storyboard and UIStoryboardSegue class 

Create subclass of UIStoryboardSegue as DismissViewController

import Foundation
import UIKit

class dismissViewController : UIStoryboardSegue {
    override func perform(){
        source.dismiss(animated: true, completion: {})

perform is UIStoryboardSegue method

now create segue from Cancel button to ViewController and make segue type as custom (if you have created subclass of UIStoryboardSegue before creating segue storyboard will show that is segue  suggestion ) for ex.

Screen Shot 2017-05-13 at 5.40.55 PM

So your Storyboard will look like (just extra segue from custom button to ViewController with segue sign as  “{}“)

Screen Shot 2017-05-13 at 5.45.09 PM.png


Hope you find this blog useful. Please feel free to contact with me in case you have any query, suggestions.  You can comment, like and follow posts.

You can request any topic related to Swift and iOS development.

Donate any small amount you think for this knowledge to grow this forum.                        

To Donate –


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s