How To Add Subview In iOS Programmatically

Some times you may need to create a SubView and add it into the root view object programmatically. This article will just show you an example about how to do it.

1. Add iOS SubView Example.

First let us look at the example demo video as below. There are two buttons, click the first button will add a subview object in the screen, click the second button will remove the added subview.

 

ios add sub view example

2. Add iOS SubView Code Steps.

  1. Create an instance of UIKit.UIView.
  2. Invoke self.vew.addSubview() method to add above instance to main screen.
  3. Call subview’s removeFromSuperview() method to remove the child view.

3. Example Code.

Below is the example project files list, the only files that we need to edit is the Main.storyboard and ViewController.swift.

ios add subview example project files list

3.1 Main.storyboard

Add two button in the main storyboard view object. Set button text, and background color to green. You can read iOS Add Click Event To UIButton Swift Example to learn how to add button click event function.

3.2 ViewController.swift

//
//  ViewController.swift
//  AddSubViewByCodeExample
//
//  Created by zhao song on 2018/8/3.
//  Copyright © 2018 dev2qa.com. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

       // Create the subview object.
       private let childView = UIView();

       // When click the second button will invoke this method.
       @IBAction func removeSubView(_ sender: UIButton, forEvent event: UIEvent) {
             // Remove the child view.
             childView.removeFromSuperview();
       }

       // Invoked when click the first button.
       @IBAction func addSubView(_ sender: UIButton, forEvent event: UIEvent) {
             // Add the child view.
             self.view.addSubview(childView);
       }
        
       override func viewDidLoad() {
             super.viewDidLoad()

             // Set child view x y cordinate and size.
             childView.frame = CGRect(x: 80, y: 100, width: 200, height: 100)

             // Set child view background color.
             childView.backgroundColor = UIColor.green
       }
}

Reference

  1. iOS Swift Hello World Example
  2. iOS Add Click Event To UIButton Swift Example
(Visited 53 times, 1 visits today)
READ :   iOS Xcode Project And Target Structure Example

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.