Swift
iOS Development
Segue
Xcode
Mobile Programming

How to segue programmatically in iOS using Swift

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In iOS development, a segue is a transition between two view controllers in your app's storyboard. While this is often done visually using Interface Builder, you might need to trigger segues programmatically under certain conditions. This could be based on user actions or data-driven logic within your app. In this article, we explore how to perform these programmatically using Swift.

Setting up Segues in Storyboard

First, you need to define a segue in your storyboard. This involves creating a connection between the source and destination view controllers. Follow these steps:

  1. Open your storyboard: Navigate to your desired view controller that will initiate the segue.
  2. Control-drag between view controllers: Hold the Control key and drag from the source view controller to the destination view controller.
  3. Select segue type: Choose the type of segue (e.g., Show, Present Modally, etc.).
  4. Assign an identifier: Select the segue and assign it an "Identifier" in the Attributes Inspector. This identifier is critical for programmatically initiating the segue.

Once you've defined the segue in storyboard, it's time to segue programmatically in your code.

Using performSegue Method

The primary method to segue programmatically is performSegue(withIdentifier:sender:). Below is a technical explanation and example of how you can use this method in a Swift project.

Example of Programmatically Triggering a Segue

Suppose you have a login screen that segues to a dashboard screen upon successful authentication. You can trigger this segue after verifying login credentials.

swift
1import UIKit
2
3class LoginViewController: UIViewController {
4    
5    // MARK: - Properties
6    @IBOutlet weak var usernameTextField: UITextField!
7    @IBOutlet weak var passwordTextField: UITextField!
8    
9    // MARK: - Actions
10    @IBAction func loginButtonTapped(_ sender: UIButton) {
11        if let username = usernameTextField.text, let password = passwordTextField.text {
12            authenticateUser(username: username, password: password)
13        }
14    }
15    
16    // MARK: - Authentication
17    func authenticateUser(username: String, password: String) {
18        // Your authentication logic here
19        if username == "admin" && password == "password" {
20            performSegue(withIdentifier: "dashboardSegue", sender: self)
21        } else {
22            // Handle authentication failure
23            showAlert(message: "Invalid username or password")
24        }
25    }
26    
27    // MARK: - Helper
28    func showAlert(message: String) {
29        let alert = UIAlertController(title: "Error", message: message, preferredStyle: .alert)
30        alert.addAction(UIAlertAction(title: "OK", style: .default))
31        present(alert, animated: true)
32    }
33}

Breaking Down the Code

  • IBOutlet properties: These connect your text fields from the storyboard to your code.
  • @IBAction for Login Button: Tied to your login button's "Touch Up Inside" event.
  • Authentication Logic: Simple check for demonstration. Replace with real authentication process.
  • Triggering Segue: performSegue(withIdentifier:sender:) uses the identifier assigned in the storyboard.
  • Displaying Alert: Presents an UIAlertController to show login errors.

Preparing for Segue

Before transitioning, you can pass data to the destination view controller by overriding the prepare(for:sender:) method. Here's an example:

swift
1override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
2    if segue.identifier == "dashboardSegue" {
3        if let destinationVC = segue.destination as? DashboardViewController {
4            destinationVC.username = usernameTextField.text
5        }
6    }
7}

Key Considerations

  • Identifier Check: Ensure you check the segue identifier to execute the correct logic.
  • Passing Data: Set properties on the destination view controller (e.g., user details).

Table: Comparison of Segue Types

Segue TypeDescriptionUse Case
ShowPushes a view controller on the navigation stack.Navigating deeper in a flow within a navigation controller.
Present ModallyPresents a view controller modally with various presentation styles like full screen or page sheet.Transitions that interrupt the current flow, like a settings or profile screen.
CustomProvides custom animations or transitions.Unique transitions that don't fit standard patterns.
UnwindReturns to a previously visited view controller, removing intermediate view controllers from the navigation stack.Useful for going back to initial or previous steps without re-entering every layer.

Conclusion

Programmatically triggering segues in an iOS app using Swift provides flexibility and control over the navigation flow, especially for condition-based transitions. With the performSegue method and prepare(for:sender:), you can efficiently manage view controller transitions while passing data between them. Ensure that you clearly define your segues in the storyboard and use identifiers wisely for smooth, bug-free navigation.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.