Effectively Dismissing a ViewController in Swift

Effectively Dismissing a ViewController in Swift

28 February 2025 Stephan Petzl Leave a comment Xcode

When working with iOS development using Swift, dismissing a ViewController can sometimes be a challenging task, especially if you’re new to the framework. This guide is designed to help you navigate the nuances of dismissing view controllers, whether they are presented modally or pushed onto a navigation stack.

Understanding the Presentation Context

Before attempting to dismiss a ViewController, it’s crucial to understand how it was presented:

  • Modal Presentation: A view controller presented modally can be dismissed using the dismiss(animated:completion:) method.
  • Push Presentation: If the view controller is part of a navigation stack, you should use navigationController?.popViewController(animated:) to return to the previous screen.

Code Solutions for Different Scenarios

Scenario 1: Dismissing a Modally Presented View Controller

When your view controller is presented modally, you can dismiss it as follows:

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

Scenario 2: Popping a View Controller from the Navigation Stack

If your view controller was pushed onto a navigation stack, you should use the following code:

self.navigationController?.popViewController(animated: true)

Practical Example

Consider a scenario where you have a Cancel button in your view controller. Depending on how this view controller was presented, you can handle the dismissal as follows:


@IBAction func cancel(sender: AnyObject) {
    if let navigationController = self.navigationController {
        navigationController.popViewController(animated: true)
    } else {
        dismiss(animated: true, completion: nil)
    }
}

Best Practices

Always ensure that you are dismissing the correct view controller, especially in complex applications where multiple view controllers might be presented simultaneously.

Enhancing Your Workflow with Repeato

For developers looking to streamline their testing process, particularly in scenarios involving UI transitions like dismissing view controllers, Repeato offers a robust solution. As a no-code test automation tool, Repeato allows you to easily record and automate these interactions, ensuring your app behaves as expected. Its support for data-driven and keyword-driven testing further enhances its capabilities, making it an excellent alternative to more complex tools like Katalon.

With Repeato, you can focus on developing your app without the hassle of managing intricate testing scripts, thus maintaining a streamlined development process.

Like this article? there’s more where that came from!