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() { super.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 myNewView.backgroundColor=UIColor.lightGray // Add rounded corners to UIView myNewView.layer.cornerRadius=25 // Add border to UIView myNewView.layer.borderWidth=2 // Change UIView Border Color to Red myNewView.layer.borderColor = UIColor.red.cgColor // Add UIView as a Subview self.view.addSubview(myNewView) } override func didReceiveMemoryWarning() { super.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.