Create UIView in Swift Programmatically

In this short blog post, you will learn how to create a UIView in Swift programmatically. The code example below will cover the following:

  • How to create UIView in Swift programmatically,
  • How to add UIView as a Subview,
  • Change UIView background color
  • Add a border around UIView,
  • Change UIView border color,
  • Make UIView corners rounded.

If you are interested in video lessons on how to write Unit tests and UI tests to test your Swift mobile app, check out this page: Unit Testing Swift Mobile App

Creating UIView Programmatically

import UIKit
class ViewController: UIViewController {
    override func viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let myNewView=UIView(frame: CGRect(x: 10, y: 100, width: 300, height: 200))
        // Change UIView background colour
        // Add rounded corners to UIView
        // Add border to UIView
        // Change UIView Border Color to Red
        myNewView.layer.borderColor =
        // Add UIView as a Subview
    override func didReceiveMemoryWarning() {
        // Dispose of any resources that can be recreated.

For more Swift code examples and tutorials, please check the Swift Code Examples page on this website.

Leave a Reply

Your email address will not be published.