관리 메뉴

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

[iOS - swift] intrinsic content size 본문

iOS 기본 (swift)

[iOS - swift] intrinsic content size

jake-kim 2020. 11. 21. 21:00

intrinsic content size란?

  • 본질적인 내용의 크기 (대부분의 View들은 기본적으로 컨텐츠의 크기만큼의 size를 가짐)
  • 예) 보통 storyboard에서 UILabel을 사용할 때, width, height contraint를 따로 지정해주지 않아도 autolayout에 아무 지장을 안주는 경우 존재
  • 예) 런타임에서 UILabel의 텍스트를 변경시켜도 autolayout에 아무 이상 없이 잘 나옴

Storyboard에서 intrinsic size변경

  • 버튼의 크기를 auto layout으로 width와 height를 지정해 놓을 수 있지만, 좋지 않은 방법

  • custom버튼의 경우 intrinsicContentSize를 override하여 font와 size등의 작업을 더욱 유연하게 할 수 있음 (아래 코드 참고)
    만약, autolayout으로 width와 height값을 강제적으로 지정해주면, Font를 바꾸는 등의 작업하기 힘듦
class TapBaseButton: UIButton {
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupView()
    }

    func setupView() {
		// some setupView...
    }

    override var intrinsicContentSize: CGSize {
        var size = super.intrinsicContentSize
        if DeviceType.iPhone5orSE {
            if let fontDescriptor = titleLabel?.font.fontDescriptor {
                titleLabel?.font = UIFont(descriptor: fontDescriptor, size: 15.0)
            } else {
                titleLabel?.font = Font.regular(size: 15.0)
            }

            size.height = 48
        } else {
            size.height = 56
        }
        return size
    }
}

invalidateIntrinsicContentSize

  • intrinsicContentSize를 참조하는 순간은 view가 updateConstraints를 호출한 직후 한번
  • 이 view 는 UIlabel의 text가 변하는것처럼 내부 사이즈가 변할때마다 invalidateIntrinsicContentSize호출
Comments