본문 바로가기
Swift

UIKit: bounds, frame

by songmoro 2023. 8. 25.
728x90

frame: The frame rectangle, which describes the view’s location and size in its superview’s coordinate system.(슈퍼뷰 좌표계에서 뷰의 위치와 크기를 설명하는 프레임 직사각형.)

bounds: The bounds rectangle, which describes the view’s location and size in its own coordinate system.(자체 좌표계에서 뷰의 위치와 크기를 설명하는 경계 직사각형.)

 

frame, bounds 사이의 차이는 좌표계의 시작이 슈퍼뷰, 자체 좌표로 나뉩니다.

 

 

let uiView = UIView()
        
let rect = CGRect(x: 50, y: 100, width: 100, height: 150)

let rectView = UIView(frame: rect)
rectView.backgroundColor = .green

uiView.addSubview(rectView)

예시를 들어 설명하면, 위 이미지의 초록 사각형 뷰 rect는 uiView라는 슈퍼뷰를 가지고 있어요.

따라서, 초록 사각형 뷰의 위치는

슈퍼뷰 기준인 frame은 x: 50, y: 100 이며, 자체 좌표 기준인 bounds는 x: 0, y: 0입니다.

print("frame :", rectView.frame.origin, rectView.frame.size)
print("bounds :", rectView.bounds.origin, rectView.bounds.size)

 

 

초록 뷰 내부에 새로운 뷰를 추가하면 frame과 bounds는 어떻게 될까요?

let subRect = CGRect(x: 10, y: 10, width: 30, height: 50)
        
let subRectView = UIView(frame: subRect)
subRectView.backgroundColor = .purple

rectView.addSubview(subRectView)

print("frame :", subRectView.frame.origin, subRectView.frame.size)
print("bounds :", subRectView.bounds.origin, subRectView.bounds.size)

위와 같이 새로운 뷰의 frame은 전체 뷰에서 위치가 아닌 슈퍼뷰에 대한 위치이고, bounds는 자체 좌표 위치인 걸 알 수 있어요.

 

 

또한, frame이 뷰의 위치와 크기를 설명하는 직사각형 프레임이라는 건 뷰가 직사각형으로 차지하는 영역의 위치와 크기를 의미합니다.

다음과 같이 뷰를 회전시키면 보라 뷰는 frame의 변화가 생기겠죠?

subRectView.transform = .init(rotationAngle: 50)
        
print("frame :", subRectView.frame.origin, subRectView.frame.size)
print("bounds :", subRectView.bounds.origin, subRectView.bounds.size)

 

 

보라 뷰에 대한 frame 값을 통해 확인하면 좀 더 이해하기 쉬울 거예요.

let borderRect = CGRect(x: 3.966138230020082, y: 6.940226482138237, width: 42.06772353995984, height: 56.11954703572353)
let borderRectView = UIView(frame: borderRect)
borderRectView.layer.borderWidth = 1

rectView.addSubview(borderRectView)

 

 

그래서 frame, bounds 중 하나의 크기를 변경하면 나머지 하나의 값 또한 새로 계산되어도 bounds를 통해 크기를 조절하거나, center를 사용해 뷰를 재배치하는 것을 권장합니다.(frame 대신 center를 사용하면 뷰가 회전되거나, 스케일링되어도 항상 동일합니다.)

 

print("before: ", subRectView.center)
subRectView.transform = .init(rotationAngle: 50)
print("after: ", subRectView.center)

 

결과물

728x90

'Swift' 카테고리의 다른 글

Simulator와 실제 디바이스 차이 - 2  (0) 2023.08.28
Simulator와 실제 디바이스 차이 - 1  (0) 2023.08.28
Vision: visionOS simulator  (0) 2023.08.22
Vision: visionOS란?  (0) 2023.08.22
SwiftUI: map, compactMap, flatMap  (0) 2023.08.11