UIKit Layout Guide

Auto Layout Update Cycle 정리

질문 포인트를 기준으로 `updateConstraints`, `setNeedsUpdateConstraints`, `setNeedsLayout`, `layoutIfNeeded`, `constraint.constant` 변경의 차이를 한 문서에서 정리한다.

Constraint update Layout / Display Practical rules
학습 날짜

기록 없음

3단계 요약: Constraint → Layout → Display

단계무엇을 하나대표 메서드
Constraint Update 제약식(관계/상수/활성화 상태)을 점검/갱신 `updateConstraints()`
Layout 제약식을 바탕으로 최종 frame(위치/크기) 계산 및 배치 `layoutSubviews()`
Display 배치된 결과를 실제로 그림 (필요 시 draw 호출) `draw(_:)`
배치(layout)와 그리기(display)는 다르다. 레이아웃은 좌표/크기 결정, 디스플레이는 픽셀 렌더링이다.

`setNeedsUpdateConstraints()`

  • "제약식을 다시 업데이트해야 함"을 예약한다.
  • 즉시 실행이 아니라 다음 update pass에서 처리된다.
  • 제약 규칙 자체가 바뀔 때 적합하다(예: `isActive` 토글).

`setNeedsLayout()`

  • "레이아웃(배치)을 다시 해야 함"을 예약한다.
  • 다음 layout pass에서 `layoutSubviews()` 중심으로 반영된다.
  • 제약 규칙은 동일하고, 배치만 다시 필요할 때 사용한다.

`constraint.constant = ...` 와 `layoutIfNeeded()`

@IBAction func didTapExpand(_ sender: UIButton) {
    heightConstraint.constant = 200   // 제약값 변경 (mutation)

    UIView.animate(withDuration: 0.25) {
        self.view.layoutIfNeeded()    // 즉시 레이아웃 반영(애니메이션)
    }
}

`updateConstraints()`를 언제 오버라이드하나

상황권장
버튼 탭 하나로 constant만 바뀜 액션 메서드에서 직접 변경 (`updateConstraints()` 오버라이드 불필요)
제약 집합 활성/비활성 전환이 많음 `setNeedsUpdateConstraints()` + `updateConstraints()`에서 최소 변경
매 패스마다 제약을 전부 껐다 켜는 구현 지양. 변경 필요한 항목만 업데이트
`updateConstraints()` 내부에서 `setNeedsUpdateConstraints()`를 다시 호출하면 피드백 루프 위험이 있다.

Q

이 섹션은 위에서 나온 질문뿐 아니라, 새로운 개발적 지식과 시니어라면 알아야 할 내용까지 추가한다.