| Term | Meaning |
|---|---|
| Frame | Position and size (x, y, width, height) |
| Auto Layout | Constraints for responsive design |
parentView.addSubview(childView)
let parentView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
parentView.backgroundColor = .lightGray
let childView = UIView(frame: CGRect(x: 50, y: 50, width: 200, height: 200))
childView.backgroundColor = .blue
parentView.addSubview(childView)
👉 Result:
Draw:
import UIKit
let myView = UIView()
myView.backgroundColor = .red
myView.frame = CGRect(x: 50, y: 100, width: 200, height: 100)
self.view.addSubview(myView)
let label = UILabel()
label.text = "Hello World"
label.frame = CGRect(x: 50, y: 100, width: 200, height: 50)
self.view.addSubview(label)
let button = UIButton(type: .system)
button.setTitle("Click Me", for: .normal)
button.frame = CGRect(x: 50, y: 200, width: 150, height: 50)
button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
self.view.addSubview(button)
@objc func buttonTapped() {
print("Button Pressed")
}
Instead of frame:
myView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
myView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
myView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
myView.widthAnchor.constraint(equalToConstant: 100),
myView.heightAnchor.constraint(equalToConstant: 100)
])
let box = UIView(frame: CGRect(x: 50, y: 100, width: 200, height: 200))
box.backgroundColor = .red
let label = UILabel(frame: CGRect(x: 20, y: 80, width: 160, height: 40))
label.text = "Inside Box"
label.textAlignment = .center
box.addSubview(label)
self.view.addSubview(box)
translatesAutoresizingMaskIntoConstraints = falseView = UI element
Subview = Child inside another view
Use addSubview() to attach views
UI can be created using:
Programmatic UI gives:
Use:
Open this section to load past papers