🍎 Swift & iOS Intermediate

What is the difference between frame-based and Auto Layout?

Why Interviewers Ask This

Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.

Answer

Two approaches to positioning and sizing UI elements in UIKit: Frame-based layout: set exact position and size manually using CGRect: let label = UILabel() label.frame = CGRect(x: 20, y: 100, width: 200, height: 44) label.text = "Hello". Works predictably, simple to understand, good performance. Problems: must recalculate manually for different screen sizes (iPhone 15 vs iPhone SE), rotations, dynamic type (accessibility text sizes). Fragile — hardcoded values break on different devices. Auto Layout: constraint-based — define relationships between views instead of exact positions: let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false view.addSubview(label) NSLayoutConstraint.activate([ label.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 16), label.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20), label.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20) ]). Adapts automatically to any screen size, orientation, and dynamic type. More complex to debug (ambiguous/conflicting constraints). Slightly more CPU-intensive to calculate. translatesAutoresizingMaskIntoConstraints: MUST be set to false when using Auto Layout programmatically — otherwise UIKit automatically adds constraints based on the view's autoresizingMask, conflicting with your constraints. Choosing: Auto Layout is standard for production apps; frame-based for performance-critical custom drawing or simple one-size scenarios. UIStackView makes common layouts much simpler. SwiftUI uses its own layout system (HStack/VStack/ZStack/Grid).

Pro Tip

If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.