create a view which is 50 by 50 in size with a green background in swift

To create a view of 50 by 50 size with a green background programmatically, you can follow these steps:

main.swift
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Create a new UIView
        let myView = UIView()

        // Set the size of the view
        myView.frame = CGRect(x: 0, y: 0, width: 50, height: 50)

        // Set the background color of the view to green
        myView.backgroundColor = UIColor.green

        // Add the view to the view hierarchy
        self.view.addSubview(myView)
    }
}
479 chars
21 lines

In this code, we create a UIView instance named myView and set its frame to a width of 50 and a height of 50. We set the background color of the view to green by setting its backgroundColor property to UIColor.green. Finally, we add the view to the view hierarchy using the addSubview method on self.view.

Note that this code creates the new view in the viewDidLoad() method of a UIViewController, but you can also create the view in a different method or class if desired.

related categories

gistlibby LogSnag