[iOS] sizeToFit vs sizeThatFits 알아보기

  sizeToFit vs sizeThatFits 알아보기


분명(?) 이 글을 읽고 있는 분도 위의 두가지 함수를 사용해본 적 있을 것 이다.
필자도 사용을 하고 있는데, 간단하게 알고 있지만, 블로그를 통해 한번 더 정리해 놓으려고 한다.

sizeToFit텍스트에 맞게 라벨의 크기가 조정됩니다.
sizeThatFits지정된 크기에 적합한 크기를 계산하여 반환합니다.
반환된 크기를 가지고 width/height 중 원하는 것만 조정할 수 있습니다.

주로 sizeThatFitsLabel, TextView높이값을 유동적으로 조정하기 위해 많이 사용됩니다.


  예제

1. Frame 을 통한 기본 Label 생성.
2. + Label SizeToFit 함수 사용.
3. Frame 조정하고, 해당 크기에 맞는 높이/넓이 값구해서 수정하기.



  Playground Sample

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white
        //
        // Label Sample
        let label = UILabel()
        label.numberOfLines = 0
        label.backgroundColor = .green
        label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
        label.text = "Hello World!" + "\n" + "line"
        label.textColor = .black
        //
        // 1. 사이즈가 텍스트에 맞게 조절됨.
        label.sizeToFit()
        //
        // 2. 텍스트에 맞게 조절된 사이즈를 가져와서 값을조정한다.
        label.frame = CGRect(x: 150, y: 200, width: 20, height: 20)
        let newSize = label.sizeThatFits(label.frame.size)
        label.frame.size.height = newSize.height
        // 주로 라벨의 height가 유동적으로 변경되야 할 경우 유용하게 사용가능할 것 같습니다.
        view.addSubview(label)
        self.view = view
    }
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
cs

댓글

댓글 쓰기

이 블로그의 인기 게시물

[iOS] 앱스토어 등록 전, 후 URL 알아보기

[Xcode] add Simulators (시뮬레이터 추가하기)

[iOS] 앱 아이콘 동적으로 변경하기 (Dynamically Change App icon)

[iOS] Device Name 가져오기 (for Swift) - 2022/09/22 update