Introduction
Layout decides where and how things appear on the screen. It helps make apps look neat and easy to use.
Layout decides where and how things appear on the screen. It helps make apps look neat and easy to use.
view.frame = CGRect(x: xPosition, y: yPosition, width: width, height: height)
// Or use Auto Layout constraints
view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
view.leadingAnchor.constraint(equalTo: parentView.leadingAnchor, constant: 20),
view.topAnchor.constraint(equalTo: parentView.topAnchor, constant: 20),
view.widthAnchor.constraint(equalToConstant: 100),
view.heightAnchor.constraint(equalToConstant: 50)
])button.frame = CGRect(x: 50, y: 100, width: 200, height: 40)
button.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
button.centerXAnchor.constraint(equalTo: view.centerXAnchor),
button.centerYAnchor.constraint(equalTo: view.centerYAnchor),
button.widthAnchor.constraint(equalToConstant: 150),
button.heightAnchor.constraint(equalToConstant: 50)
])This example creates a yellow label centered horizontally near the top of the screen using Auto Layout. It shows how layout controls where the label appears.
import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white let label = UILabel() label.text = "Hello, Layout!" label.textAlignment = .center label.backgroundColor = .systemYellow label.translatesAutoresizingMaskIntoConstraints = false view.addSubview(label) NSLayoutConstraint.activate([ label.centerXAnchor.constraint(equalTo: view.centerXAnchor), label.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 40), label.widthAnchor.constraint(equalToConstant: 200), label.heightAnchor.constraint(equalToConstant: 50) ]) } }
Using Auto Layout helps your app look good on all devices.
Frames are simple but don't adapt well to different screen sizes.
Always test your layout in both portrait and landscape modes.
Layout controls where UI elements appear on the screen.
Use frames for fixed positions, Auto Layout for flexible designs.
Good layout makes apps easier to use and nicer to look at.
VStack {
Text("Top")
Text("Middle")
Text("Bottom")
}Text("Hello")
.frame(width: 200, height: 50)
.position(x: 100, y: 25)Pass the test and this pattern moves unknown