How To Present / Dismiss UIView Controller Programmatically In Swift

When you develop iOS app use swift in Xcode, the project template commonly create a default UIViewController class defined in ViewController.swift file. This UIViewController class is used as a controller of the MVC pattern to response to the app’s main window view’s event.

But you can also create other UIViewController class and then present or dismiss it’s view in swift source code programmatically. This article will tell you how to do it with example.

1. How To Present / Dismiss UIViewController’s View In Swift Example.

First let us look at the example demo video as below.

  1. There is a yellow background button with blue text in the main UIViewController view.
  2. When you click the button, it will present the second UIViewController view.
  3. The second UIView window has red background color, and there is a Dismiss This View button in it.
  4. When you click the Dismiss This View button, it will dismiss the second UIView and return back to the main UIView.

2. How To Present / Dismiss UIViewController’s View In Swift Example Source Code.

  1. First create a Xcode project as normal use Single View App project template. You can read article How To Create A Swift Project In Xcode, How To Create Xcode Workspace And Add New / Exist Project Into It to learn more.
  2. There are three source files that need us to edit or create as below picture, they are ViewController.swift, Main.storyboard and AnotherViewController.swift file.
    present or dismiss another uiview controller example source files
  3. The ViewController.swift and Main.storyboard file are created by the project template, so you need to create the AnotherViewController.swift file ( you can refer How To Create Custom Class In Xcode Project ), this file contains a class AnotherViewController which is a sub class of UIViewController. Below is the AnotherViewController.swift file’s source code. The Dismiss This View button’s touch down event process function is implemented in the source code, you can read article How To Use One Function To Process Multiple Button Click Event Programmatically In Swift to learn how to do it.
    //
    //  AnotherViewController.swift
    //  TestProject
    //
    //  Created by song zhao on 10/12/19.
    //  Copyright © 2019 dev2qa.com. All rights reserved.
    //
    
    import UIKit
    
    class AnotherViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            
            print("Another view did load.")
            
            // Get screen width.
            let screenWidth:CGFloat = UIScreen.main.bounds.width
                    
            // Create a system default type button.
            let btn:UIButton = UIButton(type: UIButton.ButtonType.system)
            
            // Define button x, y position value.
            let btnX:CGFloat = 100
            
            let btnY:CGFloat = 100
            
            // Set this button's size and location.
            btn.frame = CGRect(x: btnX , y: btnY, width: screenWidth - 2*btnX, height: 30)
            
            // Set button background color to green.
            btn.backgroundColor = UIColor.green
            
            // Set button title.
            btn.setTitle("Dismiss This View", for: UIControl.State.normal)
            
            // Set button title color.
            btn.setTitleColor(UIColor.red, for: UIControl.State.normal)
            
            // Set button text font size.
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
            
            // Add this button touch down event process function.
            btn.addTarget(self, action: #selector(dismissButtonClickEvent(srcObj:)), for: UIControl.Event.touchDown)
            
            // Add this button to this view.
            self.view.addSubview(btn)
    
            
        }
        
        // This function will be called when the button is touch down.
        @objc func dismissButtonClickEvent(srcObj : UIButton) -> Void{
            
            // It will dismiss thie view object.
            self.dismiss(animated: true, completion: nil)
                
        }
    
       
        /* Below method will be invoked when this UIViewController is presented or dismissed. */    
        override func viewWillAppear(_ animated: Bool) {
            print("Another view will appear.")
        }
        
        override func viewDidAppear(_ animated: Bool) {
            print("Another view did appear.")
        }
        
        override func viewWillDisappear(_ animated: Bool) {
            print("Another view will disappear.")
        }
    
        override func viewDidDisappear(_ animated: Bool) {
            print("Another view did disappear.")
        }
        
        override func didReceiveMemoryWarning() {
            print("Another view receive memory warning.")
        }
    }
  4. Then edit the Main.storyboard file to add a button to it, set the button text ( Add Another View ), text color and background color. Now connect the button to a touch down event process function defined in ViewController.swift file. You can read article iOS Add Click Event To UIButton Swift Example to learn how to do.
  5. Below is the source code of ViewController.swift file.
    //
    //  ViewController.swift
    //  TestProject
    //
    //  Created by song zhao on 8/14/19.
    //  Copyright © 2019 dev2qa.com. All rights reserved.
    //
    
    import UIKit
    
    class ViewController: UIViewController {
        
        override func viewDidLoad() {
            super.viewDidLoad()
            
            print("view did load.")
            
        }
        
        override func viewWillAppear(_ animated: Bool) {
            print("view will appear.")
        }
        
        override func viewDidAppear(_ animated: Bool) {
            print("view did appear.")
        }
        
        override func viewWillDisappear(_ animated: Bool) {
            print("view will disappear.")
        }
    
        override func viewDidDisappear(_ animated: Bool) {
            print("view did disappear.")
        }
        
        override func didReceiveMemoryWarning() {
            print("view receive memory warning.")
        }
        
    
        /* This function is called when user click the Add Another View button. */
        @IBAction func addSubView(_ sender: UIButton) {
            
            print("Add another view button is clicked.")
            
            // Create another UIViewController object.
            let anotherView = AnotherViewController()
    
            
            // Set another view's background color to red.
            anotherView.view.backgroundColor = UIColor.red
            
            // Present another view object with animation.
            self.present(anotherView, animated: true, completion: nil)
            
        }
    }
    
    
READ :   How To Add, Insert, Move, Remove Sub View In iOS Swift

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.