skip to content

UIKit

UIKit is the imperative framework most shipping iOS code still uses: view controllers, Auto Layout, table and collection views, the responder chain. Interviews require it even at SwiftUI-first shops.

on this pageshow

explore

questions

page 1 of 2

In UIKit, how do you pin a view to the safe area with layout anchors, and why must translatesAutoresizingMaskIntoConstraints be set to false first?

level: juniorimportance: must knowfreq 80%

answer

  1. typed edges and dimensions
  2. returned constraints start inactive
  3. one call switches on a batch
  4. code-made views default to true
  5. bars, home indicator, extra insets

basics

~20 s

Build constraints from anchors against view.safeAreaLayoutGuide and switch them on together with NSLayoutConstraint.activate(_:). A view created in code turns its autoresizing mask into constraints by default, and those fight yours, so set translatesAutoresizingMaskIntoConstraints to false.

solid answer

~50 s

Every `UIView` and `UILayoutGuide` exposes anchors such as `leadingAnchor`, `topAnchor` and `widthAnchor`, and their `constraint(equalTo:constant:)` family returns an **inactive** `NSLayoutConstraint`. Nothing changes until you activate it, and `NSLayoutConstraint.activate(_:)` switches on a whole batch, usually more efficiently than one at a time. The anchor classes are typed, so pairing a horizontal anchor with a vertical one does not compile. To keep a trip card clear of the status bar, navigation bar, tab bar and home indicator, pin it to `view.safeAreaLayoutGuide` rather than to the view's own edges. First, though, set `translatesAutoresizingMaskIntoConstraints = false` on the subview: for views created in code it defaults to `true`, UIKit then adds constraints that reproduce the frame and autoresizing mask, and yours conflict with them. Set it from the container, not on `self`, and leave it alone on views UIKit manages, such as a stack view's arranged subviews.

code

swift · 21 lines
swift
import UIKit

final class TripViewController: UIViewController {
    private let card = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()
        card.backgroundColor = .secondarySystemBackground
        // Opt this subview out of autoresizing-mask constraints.
        card.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(card)

        let safe = view.safeAreaLayoutGuide
        NSLayoutConstraint.activate([
            card.leadingAnchor.constraint(equalTo: safe.leadingAnchor, constant: 16),
            card.trailingAnchor.constraint(equalTo: safe.trailingAnchor, constant: -16),
            card.bottomAnchor.constraint(equalTo: safe.bottomAnchor, constant: -16),
            card.heightAnchor.constraint(greaterThanOrEqualToConstant: 120)
        ])
    }
}

go deeper

for a junior

Recall the three steps: turn off translatesAutoresizingMaskIntoConstraints, add the subview, then activate anchor constraints against the safe area guide in one batch.

for a middle

Explain why the flag defaults to true for code-made views and what the generated constraints do, and why activation needs a common ancestor.

for a senior

Show the habits that prevent layout bugs in review: typed anchors, leading and trailing for right-to-left, kept references whose constant changes instead of churned constraints.

for a principal

Frame the team default: anchors and one activate call per view, never the item-attribute initializer, and a review rule against touching the flag on views UIKit manages.

## What a constraint is Auto Layout positions views by solving a set of **constraints**. Each `NSLayoutConstraint` is a linear equation of the form `item1.attribute1 = multiplier × item2.attribute2 + constant`, and the relation can also be `<=` or `>=`. Apple's documentation stresses that it is an equation, not an assignment: the solver may move either side to satisfy it. Every constraint has a **priority** between 1 and 1,000; by default it is 1,000, which means **required**. A layout is valid when the constraints have exactly one solution: more than one is *ambiguous*, none is *conflicting*. ## Anchors: the way to write constraints in code The header for `NSLayoutConstraint` says that building constraints with `init(item:attribute:relatedBy:toItem:attribute:multiplier:constant:)` is not recommended; anchors, available since iOS 9, are the replacement. Each view and each `UILayoutGuide` exposes them: - **`NSLayoutXAxisAnchor`**: `leadingAnchor`, `trailingAnchor`, `leftAnchor`, `rightAnchor`, `centerXAnchor`. - **`NSLayoutYAxisAnchor`**: `topAnchor`, `bottomAnchor`, `centerYAnchor`, `firstBaselineAnchor`, `lastBaselineAnchor`. - **`NSLayoutDimension`**: `widthAnchor` and `heightAnchor`, which also accept a constant (`constraint(equalToConstant:)`) or a multiplier of another dimension. Because `NSLayoutAnchor` is generic over its axis, `card.leadingAnchor.constraint(equalTo: other.topAnchor)` is a **compile error**, which removes a whole class of runtime mistakes. Prefer `leading` and `trailing` to `left` and `right` so the layout mirrors in right-to-left languages. ## Activating constraints Every `constraint(...)` method returns an **inactive** constraint; `isActive` is `false` for a new constraint. You turn it on by setting `isActive = true` or, for a group, with `NSLayoutConstraint.activate(_:)`, which has the same effect as setting each flag and is typically more efficient. Activation adds the constraint to the closest common ancestor of its items, so both views must already be in the same hierarchy: activating a constraint whose items share no ancestor throws an exception. To change a layout later, keep a reference and change its `constant`; the header notes this performs much better than removing a constraint and adding a near-identical one. ## translatesAutoresizingMaskIntoConstraints Before Auto Layout, views were placed with frames and an `autoresizingMask`. To let both systems coexist, UIKit can turn a view's frame and mask into constraints of its own. That is what `translatesAutoresizingMaskIntoConstraints` controls: 1. It **defaults to `true`** for every view you create in code; Interface Builder sets it to `false` for views it lays out. 2. While it is `true`, the generated constraints fix the view's size and position, so any constraint you add for size or position **conflicts** with them. 3. Set it to `false` on the subview **from the containing view or view controller**; Apple's documentation says not to set it on `self` inside a custom view, because that stops the superview managing its layout. 4. Do not change it on views UIKit manages, such as a view controller's root `view`, table view cells or a stack view's arranged subviews. ## The safe area layout guide `safeAreaLayoutGuide` (iOS 11) is a `UILayoutGuide` that marks the part of a view not covered by navigation bars, tab bars, toolbars and other ancestor content. For a view controller's root view it also accounts for the status bar and any `additionalSafeAreaInsets` the controller sets. When the view is not yet on screen, the guide's edges equal the view's edges, and they update once it appears, so constraints made in `viewDidLoad()` are still right. | Guide | What it marks | |---|---| | `safeAreaLayoutGuide` | the area free of bars and other covering content | | `layoutMarginsGuide` | the view's margins, measured from the safe area by default (`insetsLayoutMarginsFromSafeArea`) | | `readableContentGuide` | a centred width that is comfortable for reading text | | `keyboardLayoutGuide` | the space the keyboard occupies (iOS 15) | ## Mistakes that show up in review - **The flag left at `true`.** The console then reports a conflict that includes constraints UIKit generated from the frame, and the view can stay where its frame put it. - **Too many required constraints on one axis.** Pinning top and bottom *and* setting a required fixed height conflicts as soon as the space between them differs from that height; one of the three must go or become optional. - **Edges instead of the safe area.** A bottom bar pinned to `view.bottomAnchor` slides under the home indicator. - **Frames set alongside constraints.** Once a view is laid out with constraints, the next layout pass overwrites any frame you assign. ## A checklist for a trip card 1. Create the view and set `translatesAutoresizingMaskIntoConstraints = false`. 2. Call `addSubview(_:)` before creating any constraint that relates it to another view. 3. Build constraints from anchors against `view.safeAreaLayoutGuide` (or its margins). 4. Activate them in one `NSLayoutConstraint.activate(_:)` call. 5. Keep references to the constraints you will change and adjust their `constant`.

  • Why does activating a constraint between two views sometimes raise an exception?
    Activation installs the constraint on the closest common ancestor of its two items. If you create and activate it before calling `addSubview(_:)`, the views share no ancestor and UIKit throws. Add every view to the hierarchy first, then activate the batch.
  • When the trip card expands, how should its height constraint change?
    Keep a reference to the constraint and change its `constant`; the header says this performs much better than removing it and adding a new one. To animate, change the constant, then call `layoutIfNeeded()` on the common superview inside a `UIView.animate` block so the new frames are applied as part of the animation.

  • Creating an anchor constraint applies it immediately without activation.
  • translatesAutoresizingMaskIntoConstraints only matters for views from a storyboard.
  • Pinning to the view's top edge keeps content clear of the status bar.
  • A custom view should set translatesAutoresizingMaskIntoConstraints to false on itself.
  • Constraints can be activated before the two views share a superview.
  • Removing and re-adding a constraint is the normal way to change its value.
open as a page

In UIKit, how do you push and pop screens on a UINavigationController, and where does the Back button's title come from?

level: juniorimportance: must knowfreq 82%

basics

~10 s

A UINavigationController keeps a stack of view controllers: pushViewController(_:animated:) adds one on top, popViewController(animated:) removes the top one and popToRootViewController(animated:) returns to the first. The Back title comes from the previous screen's navigationItem.

open as a page

In a UIKit note editor, how do becomeFirstResponder(), resignFirstResponder() and endEditing(_:) decide whether the keyboard is on screen?

level: juniorimportance: must knowfreq 70%

basics

~20 s

UIKit shows the keyboard as the first responder's input view: becomeFirstResponder() on a text field or text view brings it up, resignFirstResponder() hides it, and endEditing(_:) resigns whichever view in a subtree is first responder.

open as a page

In a UIKit app, how do you show a new SwiftUI checkout screen inside an existing UINavigationController, and how does data reach it?

level: juniorimportance: must knowfreq 78%

basics

~20 s

Wrap the SwiftUI view in a UIHostingController(rootView:) and push that controller like any other. Data goes in through the root view's initializer or the rootView property, and events come back through closures or a shared model.

open as a page

In UIKit, how does a UITableView get its sections and rows from a UITableViewDataSource, and why must cells come from dequeueReusableCell(withIdentifier:for:)?

level: juniorimportance: must knowfreq 80%

basics

~20 s

A UITableView asks its dataSource for section and row counts, then calls tableView(_:cellForRowAt:) only for rows about to appear. dequeueReusableCell(withIdentifier:for:) returns a recycled or new cell of a registered type, so a long list keeps only about a screenful of cells.

open as a page

In UIKit, in what order do a view controller's callbacks run from loadView() to viewDidDisappear(_:), and what work belongs in each?

level: juniorimportance: must knowfreq 85%

basics

~10 s

UIKit calls loadView() and viewDidLoad() once, when the view is first needed, then viewWillAppear(:), viewIsAppearing(:) and viewDidAppear(:) on every appearance and viewWillDisappear(:) and viewDidDisappear(_:) on every disappearance. One-time setup belongs in viewDidLoad().

open as a page

In UIKit, a trip card shows a long driver name beside the fare; how do hugging and compression resistance decide which label truncates or stretches?

level: middleimportance: must knowfreq 78%

basics

~20 s

Each label's intrinsic size yields two optional constraints per axis: compression resistance against shrinking and hugging against growing. With too little room the lower compression resistance truncates; with spare room the lower hugging stretches. Equal priorities leave UIKit to choose.

open as a page

In UIKit, how should a UITabBarController hold Home, Orders and Account tabs so that each tab keeps its own navigation stack?

level: middleimportance: must knowfreq 68%

basics

~20 s

Give each tab its own UINavigationController as its root and keep the UITabBarController outside every navigation stack. Each tab then pushes and pops independently; iOS 18 adds UITab objects as another way to declare tabs.

open as a page

In UIKit, how does hitTest(_:with:) choose the view that receives a touch, and which views does it pass over?

level: middleimportance: must knowfreq 72%

basics

~20 s

UIKit's hitTest(_:with:) walks down from the window, keeping only branches whose point(inside:with:) contains the touch, and returns the deepest frontmost view; hidden views, views with interaction disabled and views with alpha below 0.01 are skipped.

open as a page

In a UIKit notes list, a UITapGestureRecognizer added to dismiss the keyboard stops table rows from being selected; why, and what fixes it?

level: middleimportance: must knowfreq 64%

basics

~20 s

A tap recognizer on the root view sees each row's touches first; when it recognizes, cancelsTouchesInView (true by default) cancels them, so the table view never sees the touch end. Set it to false, filter touches in the delegate, or use keyboardDismissMode.

open as a page

In SwiftUI, when do a UIViewRepresentable's makeUIView, updateUIView and dismantleUIView run, and how does a Coordinator act as the UIKit view's delegate?

level: middleimportance: must knowfreq 74%

basics

~20 s

makeUIView creates the UIKit view once per identity, updateUIView pushes current SwiftUI state into it whenever that state changes, and the static dismantleUIView cleans up on removal. A Coordinator, created first, is the long-lived object that serves as delegate.

open as a page

In UIKit, how do you drive a UICollectionView with UICollectionViewDiffableDataSource and NSDiffableDataSourceSnapshot, and what must the item identifiers be?

level: middleimportance: must knowfreq 70%

basics

~20 s

Create a UICollectionViewDiffableDataSource with a cell provider, build an NSDiffableDataSourceSnapshot of section and item identifiers, and call apply(_:animatingDifferences:); UIKit diffs it against what is shown. Identifiers must be unique, Hashable and stable, ideally each model's ID.

open as a page

In a scene-based UIKit app, which UISceneDelegate callbacks fire when a call screen is interrupted or backgrounded, and why don't the app delegate's equivalents fire?

level: middleimportance: must knowfreq 65%

basics

~10 s

An interruption calls sceneWillResignActive(:); going to the background calls sceneWillResignActive(:) then sceneDidEnterBackground(:); returning calls sceneWillEnterForeground(:) then sceneDidBecomeActive(_:). With scenes enabled UIKit calls these instead of the app delegate's methods, which iOS 26 deprecated.

open as a page

In UIKit, a trip card prints 'Unable to simultaneously satisfy constraints' to the console; how do you read that log and decide which constraint to make optional?

level: seniorimportance: must knowfreq 66%

basics

~20 s

The log lists required constraints that cannot all hold and names the one UIKit breaks to recover. Add up one axis, find the constraint that is really a preference, and give it an optional priority before activating it.

open as a page

In a UIKit note app, a horizontal pan on a card inside a vertical UIScrollView either blocks scrolling or never starts; how do you settle the conflict between the two recognizers?

level: seniorimportance: must knowfreq 60%

basics

~20 s

The card's pan and the scroll view's panGestureRecognizer both see the touch, and by default one recognizing blocks the other. Begin the card's pan only for mostly horizontal drags in gestureRecognizerShouldBegin(_:), and make the scroll view's pan require(toFail:) it.

open as a page

In a UIKit listings table, hearts and price-drop badges appear on the wrong homes after a fast scroll; why do reused cells keep that state, and what belongs in prepareForReuse()?

level: seniorimportance: must knowfreq 75%

basics

~20 s

UIKit hands the same cell object to the next row that scrolls in, so any field configure leaves unset keeps the previous row's value. Set every content field in tableView(_:cellForRowAt:) every time; keep prepareForReuse() for non-content resets and clearing handlers.

open as a page

In UIKit, how does UIKeyboardLayoutGuide keep a promo-code text field above the keyboard, and what keyboard-notification code does it replace?

level: middleimportance: should knowfreq 55%

basics

~20 s

Since iOS 15 every view has a keyboardLayoutGuide that tracks the docked keyboard; pinning the field's bottom to its topAnchor keeps it above the keyboard. It replaces observing keyboard frame notifications and adjusting a bottom constraint's constant by hand.

open as a page

In UIKit, how do a UIStackView's axis, distribution, alignment and spacing place a trip card's two side-by-side buttons, and when is fillEqually better than fill?

level: middleimportance: should knowfreq 62%

basics

~20 s

Axis picks a row or a column, distribution sizes views along it, alignment places them across it, and spacing sets the gaps. fill sizes buttons from their intrinsic widths and priorities; fillEqually gives both the same width whatever their titles.

open as a page

In UIKit, how do you present a basket screen as a sheet that rests at half height and expands to full height with UISheetPresentationController?

level: middleimportance: should knowfreq 62%

basics

~10 s

Present the basket in a sheet style (pageSheet or formSheet) and, before calling present, set its sheetPresentationController's detents to [.medium(), .large()]. Add prefersGrabberVisible for a grabber and selectedDetentIdentifier to choose the starting height.

open as a page

In UIKit, how does an unhandled touch or a nil-target action climb the responder chain through UIResponder's next property?

level: middleimportance: should knowfreq 58%

basics

~20 s

Unhandled events go to each UIKit responder's next: a root view's controller, otherwise the superview; a controller's view's superview; then the window, UIApplication and the app delegate. A nil-target action starts at the first responder and climbs the same chain.

open as a page

In UIKit, how does UIHostingConfiguration put a SwiftUI row inside a UICollectionView cell, and how should the row update when its data changes?

level: middleimportance: should knowfreq 48%

basics

~20 s

UIHostingConfiguration, iOS 16, is a UIContentConfiguration whose content is a SwiftUI view; you assign it to a cell's contentConfiguration. When data changes you reconfigure the item so a fresh configuration is built, or let an observed model update the row.

open as a page

In UIKit, how does UICollectionViewCompositionalLayout build a home screen with a sideways carousel, a two-column grid and a vertical list from items, groups and sections?

level: middleimportance: should knowfreq 40%

basics

~20 s

UICollectionViewCompositionalLayout nests items in groups and groups in sections, each sized with fractional, absolute or estimated dimensions. A section provider returns a different NSCollectionLayoutSection per index: one with orthogonalScrollingBehavior for the carousel, a two-item group for the grid, and a list section.

open as a page

In UIKit, how should a video call screen rearrange its participant grid on rotation and iPad window resizing, using viewWillTransition(to:with:) and trait-change registration?

level: middleimportance: should knowfreq 58%

basics

~10 s

Override viewWillTransition(to:with:) for the new size, call super, and animate the grid change inside the coordinator's animate(alongsideTransition:completion:). For size-class changes, register in viewDidLoad() with registerForTraitChanges(:handler:) (iOS 17), which replaced traitCollectionDidChange(:).

open as a page

In UIKit, why is viewIsAppearing(_:) better than viewWillAppear(_:) for work that needs the view's size or traits, and which iOS releases can call it?

level: middleimportance: should knowfreq 55%

basics

~20 s

viewWillAppear(:) runs before the view joins the hierarchy, so traits, size and safe area may be stale; viewIsAppearing(:) runs just after, once per appearance, with all of them valid. It shipped in the iOS 17 SDK and back-deploys to iOS 13.

open as a page

In UIKit, a custom fare badge view overrides intrinsicContentSize, yet keeps its old width after the fare text changes; why, and what is the fix?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Auto Layout uses the intrinsicContentSize it last read until the view says it changed, and the badge never said so. Call invalidateIntrinsicContentSize() whenever the text changes; setNeedsLayout() or setNeedsDisplay() alone rerun layout or drawing with the old size.

open as a page

In UIKit, a custom push animator grows a dish photo into its detail screen, but afterwards the app is stuck and Back does nothing; what is wrong, and how should the animator work?

level: seniorimportance: should knowfreq 32%

basics

~10 s

The animator never called completeTransition(_:) on its transition context, so UIKit never finished the push. An animator adds the incoming view to containerView, animates it, and ends every path with completeTransition(!transitionWasCancelled).

open as a page

In UIKit, after a user swipes a basket page sheet away, the menu screen's viewWillAppear never runs and its basket badge stays stale; why, and how do you fix it?

level: seniorimportance: should knowfreq 50%

basics

~20 s

A page or form sheet leaves the menu visible, so UIKit never sends it viewWillDisappear or viewDidDisappear and has no reappearance to report. Refresh in presentationControllerDidDismiss(_:) for swipes and in your dismiss completion for code.

open as a page

In a UIKit note app, a floating toolbar's small buttons are hard to hit and its pop-out colour palette ignores taps; how do you fix both with point(inside:with:)?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Hit testing searches a subview only if its superview's point(inside:with:) contains the touch, so a palette outside the toolbar's bounds is unreachable. Override the toolbar's point(inside:with:) to claim its subviews' frames, and the buttons' to test an outset bounds.

open as a page

A SwiftUI store-locator screen wraps MKMapView in a UIViewRepresentable with a region binding, and the map jitters and re-centres endlessly; what causes the loop and how do you fix it?

level: seniorimportance: should knowfreq 55%

basics

~20 s

updateUIView sets the map's region from the binding, the map reports its slightly adjusted region through the delegate, the coordinator writes it back, and SwiftUI calls updateUIView again. Break the cycle by skipping values the map itself just reported.

open as a page

In UIKit, a SwiftUI banner hosted in a UIHostingController inside a UIStackView keeps its first size after its text changes; why, and how do sizingOptions fix it?

level: seniorimportance: should knowfreq 50%

basics

~20 s

Auto Layout keeps using a view's intrinsic content size until the view invalidates it. Setting the hosting controller's sizingOptions to .intrinsicContentSize, iOS 16, makes its view invalidate that size when the SwiftUI content's ideal size changes.

open as a page

showing 1–30 of 36