관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift] Autolayout과 translatesAutoresizingMaskIntoConstraints 이해하기 (Autoresizing Mask) 본문

iOS 응용 (swift)

[iOS - swift] Autolayout과 translatesAutoresizingMaskIntoConstraints 이해하기 (Autoresizing Mask)

jake-kim 2024. 2. 7. 01:51

Autolayout 동작 방식

  • Autolayout은 superview의 크기가 변경되면, constraints로 잡혀있는 값을 기준으로 본인의 크기를 적절하게 변화시키는 것
    • ex) 사용자가 iPhone을 회전하는 경우, superview인 window의 가로와 세로가 변경되므로 그 subview들은 모두 크기를 변화시킴
  • constraints로 위치와 크기에 관한 (x, y, width, height) 기준이 정해지면, superview가 변할때 언제든지 동적으로 변동이 가능

Autoresizing Mask 개념

  • bit mask를 사용
    • * bit mask: 2진수로 표현한 값이며, 0001은 width값, 0011은 height값 이렇게 값을 표현하는 방법 (enum형태)
    • ex) 아래는 flexibleWidth라는 bit mask를 사용한 것 
let v = UIView()
v.autoresizingMask = .flexibleWidth

* 왜 bit mask라 하는 것인지?

  • 2진수는 OR 연산자, AND 연산자 등을 수행할 때, 컴퓨터가 매우 쉽게 계산을 할 수 있기 때문
  • ex) flexibleWidth, flexibleHeight, 입력된 값들을 다 적용하고 싶은 경우 OR연산자를 사용

AutoresizingMask보다 AutoLayout가 좋은 이유

  • autolayout이 더 좋은 점
    • safe area와 margin 설정을 편하게 설정이 가능
    • 보다 손쉽게 layout 설정이 가능
    • autoresizingMask는 뷰 간의 종속적으로 표현이 어렵지만 autoLayout은 가능

AutoresizingMask는 언제 사용하는지?

  • 프로토타입으로만 사용할 것 (간단한 단일 뷰의 레이아웃을 빠르게 만들어보고 싶은 경우)

translatesAutoresizingMaskIntoConstraints 이해하기

  • true로 설정한 경우
    •  크기와 위치는 부모 뷰나 슈퍼뷰의 bounds나 frame에 따라 결정 (iOS 6 이전의 방식)
translatesAutoresizingMaskIntoConstraints = true
  • false로 설정한 경우
    • frame 기반이 아닌, constraints 기반으로 뷰가 조정 (autolayout)
    • (Interface Builder를 사용하면 디폴트가 false로 지정되고, 코드로 뷰를 만들면 디폴트는 true임을 주의)
translatesAutoresizingMaskIntoConstraints = false

애플에서 translatesAutoresizingMaskIntoConstraints라고 이름을 지은 이유?

* translate A into B: A를 B로 해석하다

  • 의미를 보면, "AutoresizingMask를 Constraints로 해석한다"라는 의미
  • Constraints라는 단어의 주의사항
    • AutoLayout에서 anchor를 가지고 Constraints설정을 하는데, 이 때의 Constraints와 translatesAutoresizingMaskIntoConstraints에서의 Constraints 다른 것임을 주의
    • Constraints는 단순히 뷰를 표현할때의 제약이라는 의미이고 Constraints가 곧 AutoLayout이라고 생각하면 안됨
  • 즉, autoresizingMask를 뷰의 제약으로 설정하면(true) autoresizingMask를 사용한다는 것이고, autoresizingMask를 뷰의 제약으로 설정하지 않으면(false) autoLayout을 사용한다는 의미
// "autoresizingMask를 뷰의 제약으로 사용하지 않는다" == (다른 방법으로 제약을 사용할 것이다)
translatesAutoresizingMaskIntoConstraints = false

* 참고

- https://developer.apple.com/documentation/uikit/uiview/1622572-translatesautoresizingmaskintoco

- https://www.advancedswift.com/autolayout-vs-autoresizing-masks/

- https://developer.apple.com/documentation/uikit/uiview/1622559-autoresizingmask

Comments