How To Add, Insert, Move, Remove Sub View In iOS Swift

A swift view can have subviews, the subview can have it’s own subview also. So you can implement a view tree in swift, all the subviews are saved in a subview array, later added subview will override previously added subview. This article will show you an example to tell you how to add, insert, move and remove subview in iOS swift code.

1. Manage Swift View And Subview Example Demo.

  1. First, let us look at this example in a video as below.
  2. When the app starts, there are three color views and six buttons.
  3. The green view is located at the backend and the red view is located at the front, the blue view is a subview of the red view.
  4. So you can see the blue view override the red view and the red view override the green view.
  5. When you click the first button, it will change the three views’ alpha values to change their transparency one by one.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/Rc_g9ti-Nbc

  1. When you click the second button, it will insert a yellow view in front of the green view and at the backend of the red view.

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

  1. When you click the third button, it will bring the yellow view to the front of the screen.

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

  1. When you click the fourth button, it will send the yellow view to the backend of the green view.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/o-4MDkwske4

  1. When you click the fifth button, it will exchange the yellow view and the red view location.

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

  1. When you click the last button, it will remove the yellow view from the screen.

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

2. Manage Swift Subview Functions Introduction.

  1. parentViewObject.addSubview( subView : UIView ) : Add a subview to parent view.
  2. parentViewObject.insertSubview( subView : UIView, belowSubView: UIView ) : Insert a subview below specified subview in the parent view.
  3. parentViewObject.bringSubviewToFront( subView : UIView ) : Bring the specified subview to the front of parent view.
  4. parentViewObject.sendSubviewToBack( subView : UIView ) : Send the specified subview to the backend of parent view.
  5. parentViewObject.exchangeSubview( at : Int, withSubviewAt: Int ) : Exchange two subviews in same parent view by subview index.
  6. subViewObject.removeFromSuperview() : Remove the subview from it’s parent view.

3. Manage Swift Subview Example Source Code.

  1. Below is this example project source files list. You can see each button has a referencing outlet and an action event process function.
  2. Below is the source code of ViewController.swift file.
    //
    //  ViewController.swift
    //  ManageSubViewExample
    //
    //  Copyright © 2019 dev2qa.com. All rights reserved.
    //
    
    import UIKit
    
    class ViewController: UIViewController {
        
        // Save current displayed color view index.
        var currViewIndex : Int = 0;
        
        // Create green view, red view, yellow view and blue view.
        let greenView : UIView = createRectView(x: 100, y: 200, width: 150, height: 300, color: UIColor.green, transparency: 1)
        
        let redView : UIView = createRectView(x: 150, y: 250, width: 150, height: 300, color: UIColor.red, transparency: 1)
        
        let blueView : UIView = createRectView(x: 50, y: 50, width: 90, height: 200, color: UIColor.blue, transparency: 1)
        
        let yellowView : UIView = createRectView(x: 125, y: 225, width: 150, height: 300, color: UIColor.yellow, transparency: 1)
        
        // These UILabel is used to display message when user click the first button.
        @IBOutlet weak var changeAlphaMessage: UILabel!
        
        // These UIButton object is connected with the six button as outlet.
        @IBOutlet weak var changeAlphaButton: UIButton!
        
        @IBOutlet weak var insertViewButton: UIButton!
        
        @IBOutlet weak var bringViewToFrontButton: UIButton!
        
        @IBOutlet weak var sendViewToBackButton: UIButton!
        
        @IBOutlet weak var exchangeViewButton: UIButton!
        
        @IBOutlet weak var removeViewButton: UIButton!
        
        override func viewDidLoad() {
            
            // Change the six button to rounded border button.
            changeButtonToRoundedBorder(button: changeAlphaButton)
            
            changeButtonToRoundedBorder(button: insertViewButton)
            
            changeButtonToRoundedBorder(button: bringViewToFrontButton)
            
            changeButtonToRoundedBorder(button: sendViewToBackButton)
            
            changeButtonToRoundedBorder(button: exchangeViewButton)
            
            changeButtonToRoundedBorder(button: removeViewButton)
        
            
            // Clear the label text when app initialize.
            changeAlphaMessage.text = ""
        
            super.viewDidLoad()
            
            // Add blue view as red view's subview. So all the blue view's coordinate value is relative to the red view.
            redView.addSubview(blueView)
            
            // Add green view and red view to the app root view.
            self.view.addSubview(greenView)
            
            self.view.addSubview(redView)
            
            // Print red view's subviews array.
            for subView in redView.subviews{
                print(subView)
            }
            
            print(redView.subviews)
            
        }
    
        
        /* This function will be invoked when the Change SubView Alpha Value One By One button is clicked. */
        @IBAction func changeSubViewAlpha(_ sender: UIButton, forEvent event: UIEvent) {
            
            if(currViewIndex == 0){
                
                changeAlphaMessage.text = "Change green view alpha value."
                
                greenView.alpha = 0.5
                redView.alpha = 1
                blueView.alpha = 1
            }else if(currViewIndex == 1)
            {
                
                changeAlphaMessage.text = "Change red view alpha value."
                
                greenView.alpha = 1
                redView.alpha = 0.5
                blueView.alpha = 1
            }else if(currViewIndex == 2)
            {
                changeAlphaMessage.text = "Change blue view alpha value."
                
                greenView.alpha = 1
                redView.alpha = 1
                blueView.alpha = 0.5
            }
            
            currViewIndex += 1
            
            if(currViewIndex > 2){
                currViewIndex = 0
            }
        }
    
        
        /* This function will be invoked when 'Insert A Yellow View Above Green View' button is clicked.*/
        @IBAction func insertView() {
            
            self.view.insertSubview(yellowView, belowSubview: redView)
        
        }
    
        
        /* When click the 'Bring Yellow View To Front' button, this function will be invoked. */
        @IBAction func bringYellowViewToFront() {
            
            self.view.bringSubviewToFront(yellowView)
            
        }
    
        
        /* When click the 'Exchange Yellow & Red View' button, this function will be invoked. */
        @IBAction func exchangeYellowAndRedView(_ sender: UIButton) {
        
            let yellowViewIndex:Int = self.view.subviews.firstIndex(of: yellowView)!
            
            let redViewIndex:Int = self.view.subviews.firstIndex(of: redView)!
    
            
            self.view.exchangeSubview(at: yellowViewIndex , withSubviewAt: redViewIndex)
        }
    
        
         /* When click the 'Send Yellow View To Back' button, this function will be invoked. */
        @IBAction func sendYellowViewToBack() {
            self.view.sendSubviewToBack(yellowView)
        }
    
        
         /* When click the 'Remove Yellow View' button, this function will be invoked. */
        @IBAction func removeYellowView() {
            
            yellowView.removeFromSuperview()
        }
    
        
        /* This function will create a rectangle view with provided parameters. */
        static func createRectView(x:Float, y:Float, width:Float, height:Float, color: UIColor, transparency
            
    : Float) -> UIView{
            
            let viewRectFrame = CGRect(x:CGFloat(x), y:CGFloat(y), width:CGFloat(width), height:CGFloat(height))
            
            let retView = UIView(frame:viewRectFrame)
            
            retView.backgroundColor = color
            
            retView.alpha = CGFloat(transparency)
            
            return retView
        }
    
        
        /* This function will change button to a rounded border button. */
        func changeButtonToRoundedBorder(button:UIButton){
            /* Below code will make the button rounded border. And the button background color is transparent. */
            
            // Clear button background color.
            button.backgroundColor = UIColor.clear
            
            // Set button rounded corner radius.
            button.layer.cornerRadius = 10
            
            // Set button border width.
            button.layer.borderWidth = 2
            
            // Set button border color.
            button.layer.borderColor = UIColor.black.cgColor
        }
    
    
    }
    

References

  1. iOS Add Click Event To UIButton Swift Example
  2. How To Create A Swift Project In Xcode
  3. How To Make Rounded Border Button In Swift
  4. How To Connect Storyboard UI Component To ViewController Class Code

Leave a Comment

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.