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

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.

       // Invoked when click the first button.
       @IBAction func addSubView(_ sender: UIButton, forEvent event: UIEvent) {
             // Add the child view.
       override func 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 =


  1. iOS Swift Hello World Example
  2. iOS Add Click Event To UIButton Swift Example
0 0 vote
Article Rating
Notify of

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

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x