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

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

1. Manage Swift View And Subview Example Demo.

First let us look at this example in a video as below. When the app start, there are three color view and six button. The green view locate at backend and the red view locate at front, the blue view is a subview of red view, so you can see the blue view override the red view and the red view override the green view. When you click the first button, it will change the three color view’s alpha value to change their transparency one by one.

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

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

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

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

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

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.
READ :   How To Use Swift Closures Example

3. Manage Swift Subview Example Source Code.

Below is this example project source files list. You can see each button has a reference outlet and an action event process function.

manage subview xcode project files list

Below is the source code of ViewController.swift file.

//
//  ViewController.swift
//  ManageSubViewExample
//
//  Created by song zhao on 6/20/19.
//  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 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.