Notice
Recent Posts
Recent Comments
Link
관리 메뉴

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

[iOS - swift] AutoresizingMask, translatesAutoresizingMaskIntoConstraints 개념 본문

iOS 기본 (swift)

[iOS - swift] AutoresizingMask, translatesAutoresizingMaskIntoConstraints 개념

jake-kim 2021. 8. 22. 22:19

AutoresizingMask

  • superview의 bounds가 변경될때 subview의 크기를 어떻게 크기를 재설정 할것인가에 대한 bit mask
    • bit mask: 컴퓨터의 언어인 이진수를 사용하면 연산이 빠른점을 이용해 어떤 정수를 이준수 형태로 표현하여 자료구조로써 사용하는 기법
  • 원리: view의 bounds가 변경되면 subview들을 각 subview의 autoresizing mask에 해당되는 부분을 자동으로 재설정
    • UIView.AutoresizingMask에 설명된 상수를 결합하여 값을 조정

UIView.AutoresizingMask

  • default값은 flexibleWidth와 flexibleRightMargin 상수가 포함되어 있지만, flexibleLeftMargin상수는 포함되어 있지않기 때문에 뷰가 왼쪽에 고정되어 있는 것으로 가정

Autoresizing 개념

  • Autoresizing mask를 사용하여, superview가 커지거나 줄어듦에 따라 subview의 크기나 위치를 조정
  • Autoresizing을 사용하지 않은 경우
class ViewController: UIViewController {

    lazy var sampleSuperview: UIView = {
        let view = UIView(frame: CGRect(origin: .zero, size: CGSize(width: 200, height: 200)))
        view.backgroundColor = .darkGray

        return view
    }()

    lazy var sampleSubview: UIView = {
        let view = UIView(frame: CGRect(origin: CGPoint(x: 50, y: 50), size: CGSize(width: 100, height: 100)))
        view.backgroundColor = .lightGray

        return view
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        sampleSuperview.center = view.center
        view.addSubview(sampleSuperview)
        sampleSuperview.addSubview(sampleSubview)

        UIView.animate(withDuration: 1.5) {
            self.sampleSuperview.bounds.size = CGSize(width: 300, height: 300)
        }
    }
}

디폴트가 내부적으로 flexibleLeftMargin는 포함되어 있지 않음 > 왼쪽에 고정

  • 왼쪽에 margin부여
sampleSubview.autoresizingMask = [.flexibleLeftMargin]

  • 크기 부여
sampleSubview.autoresizingMask = [.flexibleWidth, .flexibleHeight]

translatesAutoresizingMaskIntoConstraints 개념

  • autoresizingMask는 superview가 변함에 따라 subview의 크기를 어떻게 할것인가이기 때문에, 이와 동일한 기능을 하는 autolayout에서 같이 사용된다면 충돌이 날 수 있는것 > 충돌 방지를 위해 Auturesizing을 사용하지 않는것으로 명시적 선언
subview.translatesAutoresizingMaskIntoConstraints = false
  • Storyboard에서는 autolayout을 사용하면 자동으로 false로 설정

* 참고

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

- https://developer.apple.com/documentation/appkit/nsview/1526961-translatesautoresizingmaskintoco

Comments