How To Present / Dismiss UIView Controller Programmatically In Swift

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

But you can also create another 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 an example.

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

If you can not watch the above video, you can see it on URL https://youtu.be/VYRwQ3yTx9o

  1. First, let us look at the example demo video above.
  2. There is a yellow background button with blue text in the main UIViewController view.
  3. When you click the button, it will present the second UIViewController‘s view.
  4. The second UIView window has a red background color, and there is a Dismiss This View button in it.
  5. 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 an Xcode project as normal use the Single View App project template. You can read the 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, they are ViewController.swift, Main.storyboard and AnotherViewController.swift file.
  3. The ViewController.swift and the Main.storyboard files are created by the project template, so you need to create the AnotherViewController.swift file ( you can refer to How To Create Custom Class In Xcode Project ), this file contains a class AnotherViewController which is a subclass of UIViewController.
  4. 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 the article How To Use One Function To Process Multiple Button Click Event Programmatically In Swift to learn how to do it.
    //
    //  AnotherViewController.swift
    //  TestProject
    //
    //  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.")
        }
    }
  5. Then edit the Main.storyboard file to add a button to it, set the button text ( Add Another View ), text color, and background color.
  6. Now connect the button to a touch-down event process function defined in ViewController.swift file. You can read the article iOS Add Click Event To UIButton Swift Example to learn how to do it.
  7. Below is the source code of ViewController.swift file.
    //
    //  ViewController.swift
    //  TestProject
    //
    //  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)
            
        }
    }
    
0 0 votes
Article Rating
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x