[ios] How to dismiss ViewController in Swift?

I am trying to dismiss a ViewController in swift by calling dismissViewController in an IBAction

  @IBAction func cancel(sender: AnyObject) {
    self.dismissViewControllerAnimated(false, completion: nil)
    println("cancel")
}

@IBAction func done(sender: AnyObject) {
    self.dismissViewControllerAnimated(false, completion: nil)
    println("done")
}

random image of a segue

I could see the println message in console output but ViewController never gets dismissed. What could be the problem?

This question is related to ios swift viewcontroller

The answer is


Since you used push presented viewController, therefore, you can use

self.dismiss(animated: false, completion: nil)

So if you wanna dismiss your Viewcontroller use this. This code is written in button action to dismiss VC

  @IBAction func cancel(sender: AnyObject) {
   dismiss(animated: true, completion: nil)
  }

For reference, be aware that you might be dismissing the wrong view controller. For example, if you have an alert box or modal showing on top of another modal. (You could have a Twitter post alert showing on top of your current modal alert, for example). In this case, you need to call dismiss twice, or use an unwind segue.


In Swift 3.0 to 4.0 it's as easy as typing this into your function:

self.dismiss(animated: true, completion: nil)

Or if you're in a navigation controller you can "pop" it:

self.navigationController?.popViewController(animated: true)

  1. embed the View you want to dismiss in a NavigationController
  2. add a BarButton with "Done" as Identifier
  3. invoke the Assistant Editor with the Done button selected
  4. create an IBAction for this button
  5. add this line into the brackets:

    self.dismissViewControllerAnimated(true, completion: nil)
    

If you are presenting a ViewController modally, and want to go back to the root ViewController, take care to dismiss this modally presented ViewController before you go back to the root ViewController otherwise this ViewController will not be removed from Memory and cause Memory leaks.


Use:

self.dismiss(animated: true, completion: nil)

instead of:

self.navigationController.dismissViewControllerAnimated(true, completion: nil)

From Apple documentations:

The presenting view controller is responsible for dismissing the view controller it presented

Thus, it is a bad practise to just invoke the dismiss method from it self.

What you should do if you're presenting it modal is:

presentingViewController?.dismiss(animated: true, completion: nil)

If you presenting a controller without a Navigation Controller, you can call the following code from a method of the presented controller.

self.presentingViewController?.dismiss(animated: true, completion: nil)

If your ViewController is presented modally, optional presentingViewController will be not nil and the code will be executed.


I have a solution for your problem. Please try this code to dismiss the view controller if you present the view using modal:

Swift 3:

self.dismiss(animated: true, completion: nil)

OR

If you present the view using "push" segue

self.navigationController?.popViewController(animated: true)

If you using the present method in the parent VC then you should call this function, to dismiss the child VC use this

self.dismiss(animated: true, completion: nil)

if you calling child VC by using push method, to dismiss the child VC use this

self.navigationController?.popViewController(animated: true)

In Swift 3.0

If you want to dismiss a presented view controller

self.dismiss(animated: true, completion: nil)

Try this:

@IBAction func close() {
  dismiss(animated: true, completion: nil)
}

Here is the one way to dismiss present view controller and move back to previous view controller. You can do this through Storyboard only.

  1. Open Storyboard
  2. Right click on Cancel button and drag it to previous view controller, where you want to move back to previous controller
  3. Now release the right click and you can see some actions which performs on cancel button
  4. Now choose "popover present" option from list
  5. Now you can dismiss your current view by click on cancel button

Please try this, It's working with me.

Second Way - Use - navigationController.popViewControllerAnimated(true)

Best luck..


@IBAction func back(_ sender: Any) {
        self.dismiss(animated: false, completion: nil)
    }

In Swift 4.1 and Xcode 9.4.1

If you use pushViewController to present new view controller, use this

self.navigationController?.popViewController(animated: false)

Based on my experience, I add a method to dismiss me as extension to UIViewController:

extension UIViewController {
    func dismissMe(animated: Bool, completion: (()->())?) {
        var count = 0
        if let c = self.navigationController?.viewControllers.count {
            count = c
        }
        if count > 1 {
            self.navigationController?.popViewController(animated: animated)
            if let handler = completion {
                handler()
            }
        } else {
            dismiss(animated: animated, completion: completion)
        }
    }
}

Then I call this method to dismiss view controller in any UIViewController subclass. For example, in cancel action:

class MyViewController: UIViewController {
   ...
   @IBAction func cancel(sender: AnyObject) {
     dismissMe(animated: true, completion: nil)
   }
   ...
}

if you do this i guess you might not get println message in console,

@IBAction func cancel(sender: AnyObject) {
  if(self.presentingViewController){
    self.dismissViewControllerAnimated(false, completion: nil)
    println("cancel")
   }
}

@IBAction func done(sender: AnyObject) {
  if(self.presentingViewController){
    self.dismissViewControllerAnimated(false, completion: nil)
    println("done")
  }    
}

Don't create any segue from Cancel or Done to other VC and only write this code your buttons @IBAction

@IBAction func cancel(sender: AnyObject) {
    dismiss(animated: false, completion: nil)
}

Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to swift

Make a VStack fill the width of the screen in SwiftUI Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Command CompileSwift failed with a nonzero exit code in Xcode 10 Convert Json string to Json object in Swift 4 iOS Swift - Get the Current Local Time and Date Timestamp Xcode 9 Swift Language Version (SWIFT_VERSION) How do I use Safe Area Layout programmatically? How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator Safe Area of Xcode 9 The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

Examples related to viewcontroller

Presenting modal in iOS 13 fullscreen Swift programmatically navigate to another view controller/scene Swift: Reload a View Controller How do I create a view controller file after creating a new view controller? presenting ViewController with NavigationViewController swift Programmatically switching between tabs within Swift How to dismiss ViewController in Swift? Swift presentViewController How to Navigate from one View Controller to another using Swift