[TIL] Autolayout

Eden·2025년 6월 11일

Frame-Based Layout

  • Autolayout 등장 이전의 UI 배치 방식
  • frame 설정을 통해 View의 위치와 크기를 수동으로 결정
  • 단점: 레이아웃이 바뀔 때마다 직접 재배치가 필요함

Autolayout

  • View의 위치나 크기를 다른 객체에 상대적으로 제약(Constraint)을 줘서 배치

  • 사용 가능한 Attribute:

    • leading, trailing, left, right, top, bottom
    • centerX, centerY, center, width, height
  • leading: 왼쪽

  • trailing: 오른쪽

중요 키워드

  • translatesAutoresizingMaskIntoConstraints = false 로 설정해야 Autolayout 적용 가능
  • 기본값은 .flexibleRightMargin
    → 왼쪽 마진은 유지, 오른쪽 마진은 유연하게 변화
  • .flexibleLeftMargin: 왼쪽이 유연하게 변화
  • .flexibleWidth, .flexibleHeight: 부모 크기에 맞게 동적으로 변화
  • true일 경우 AutoresizingMask와 Constraint가 충돌해서 Auto Layout 비활성화됨

Safe Area

  • iOS에서 상단바, 하단바 등 시스템 UI를 제외한 안전한 영역

intrinsicContentSize

  • View가 가진 고유의 본래 크기
  • 예시:
View TypeWidthHeight
UIView
UISlider
UILabel, UIButton, UISwitch, UITextField
UITextView, UIImageView콘텐츠에 따라 결정됨
  • invalidateIntrinsicContentSize()
    → 콘텐츠 변경 시 intrinsic size를 갱신해 Auto Layout 업데이트

Priority

  • View에 우선순위를 부여하는 개념

Content Hugging Priority

  • setContentHuggingPriority(_:for:)
  • View가 커지지 않도록 하는 우선순위
  • "나 안 늘어나고 싶어"

Compression Resistance Priority

  • View가 줄어들지 않도록 하는 우선순위

  • "나 안 줄어들고 싶어"

  • 시스템 기본값:

    • .defaultLow: 250
    • .defaultHigh: 750
    • .required: 1000

퍼센트 레이아웃

  • 퍼센트 기반 레이아웃은 AutoLayout에서 multiplier를 사용해야 함
leftLabel.widthAnchor.constraint(equalTo: container.widthAnchor, multiplier: 0.3)
rightLabel.widthAnchor.constraint(equalTo: container.widthAnchor, multiplier: 0.7)
profile
iOS Dev

0개의 댓글