Contact
← Back to Topics

Layout Constraints

Rules that define how UI elements are positioned and sized relative to each other.

About Layout Constraints

Layout constraints are rules that define how UI elements are positioned and sized relative to each other, forming the basis of Auto Layout in iOS. They allow developers to create adaptive interfaces that respond to different screen sizes and orientations.

Key Features

  • Mathematical expressions of relationships
  • Priority-based resolution
  • Intrinsic content size handling
  • Constraint activation/deactivation
  • Visual Format Language support

Code Example

// Layout constraints example
// Method 1: NSLayoutConstraint
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
parentView.addSubview(view)

NSLayoutConstraint.activate([
    // Center horizontally
    view.centerXAnchor.constraint(equalTo: parentView.centerXAnchor),
    
    // Position from top
    view.topAnchor.constraint(equalTo: parentView.topAnchor, constant: 50),
    
    // Set size
    view.widthAnchor.constraint(equalToConstant: 200),
    view.heightAnchor.constraint(equalToConstant: 100)
])

// Method 2: Visual Format Language
let views = ["view": view]
let horizontalConstraints = NSLayoutConstraint.constraints(
    withVisualFormat: "H:|-[view(200)]-|",
    options: [],
    metrics: nil,
    views: views
)
let verticalConstraints = NSLayoutConstraint.constraints(
    withVisualFormat: "V:|-50-[view(100)]",
    options: [],
    metrics: nil,
    views: views
)
NSLayoutConstraint.activate(horizontalConstraints + verticalConstraints)