iOS

UIKit: Frame과 Bounds 1

Dev Arthur 2025. 1. 5. 21:25

UIKit으로 UI를 그리다 보면 심심찮게 보이는

FrameBounds

 

막상 사용해보면 큰 차이를 못 느낀다...

공식 문서를 살펴보면

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.
자신의 좌표계 안에서 뷰의 위치와 크기를 표현하는 사각형 범위

 

뭔가 같으면서도 다른 느낌...?

 

자세하게 알아보기전에 UIKit의 좌표계에 대해 짚고 넘어가면

좌측 상단을 원점(0,0)으로 하고 우측 또는 하단으로 가면 확장되는 좌표계이다.

 

다시 돌아와서,

기본 코드는 아래와 동일하고 Frame Bounds를 설정하는 코드만 다르게 할 것이다.

override func viewDidLoad() {
    super.viewDidLoad()
    
    // 부모뷰의 배경색 설정
    self.view.backgroundColor = .green
    
    // 부모뷰에 자식뷰 삽입
    self.view.addSubview(self.childView)

	// 자식뷰의 배경색 설정
    self.childView.backgroundColor = ...
}
self.childView.frame = .init(x: 0, y: 0, width: 100, height: 100)

self.childView.bounds = .init(x: 0, y: 0, width: 100, height: 100)

 

 

크기를 동일하게 줬지만 뭔가 이상하다.

그래서 각 상황에 Frame과 Bounds를 출력해 보았다.

 

Frame만 잡은 경우,

 

Bounds만 잡은 경우,

 

여기서 2가지 의문이 생겼다.

  1. Frame만 잡거나 Bounds만 잡았을 때, 설정하지 않은 쪽 값도 같이 설정되어 있는가?
  2. Bounds만 잡은 경우에 Frame의 좌표 값이 왜 이상한 값(?)이 되는가?

1번 의문부터 해결하기 위해

Frame과 Bounds의 설명을 좀 더 살펴보면

Frame
Setting this property changes the point specified by the 
center property and changes the size in the bounds rectangle accordingly.
이 프로퍼티(Frame)를 설정하면, center에 의해 지정된 점과 bounds의 크기가 변한다.
Bounds
Changing the size portion of this rectangle grows or shrinks the view relative to its center point.
Changing the size also changes the size of the rectangle in the frame  property to match.
(Bounds의) 크기 부분을 바꾸면, 뷰가 중심점을 기준으로 늘어난다.
또한, Frame 프로퍼티의 크기 부분을 바꾼다.

 

이를 통해서, FrameBounds 그리고, Center(?)

3가지 프로퍼티가 상호 영향을 주는 관계인 것을 알 수 있다.

 

그래서, Frame과 Bounds의 크기가 서로 동기화되는 것!

 

자 다음, 2번 의문을 해결하기 위해 Center에 대해 살펴보면

Center
The center point of the view’s frame rectangle.
뷰의 사각형 틀의 중심점
Setting this property updates the origin of the rectangle in the frame property appropriately.
...
Use this property, instead of the 
frame property, when you want to change the position of a view. The center point is always valid,
이 프로퍼티(Center)를 설정하는 건, Frame 프로퍼티의 origin(좌표)를 업데이트한다.
...
Frame 프로퍼티 말고, 뷰의 위치를 바꾸고 싶다면 이 프로퍼티(Center)를 이용해라
Center는 항상 유효하다

 

그래서 정리해 보자면

Frame을 설정하지 않을 경우, Center를 통해 좌표를 설정하게 되고

Bounds를 통해 크기를 설정하면, Cetner를 기준으로 크기가 늘어난다.

Frame에서 좌표는 UIKit에서 기준으로 잡고 있는 좌측 최상단,

FrameBounds를 설정하지 않았을 때, Center의 기본값은 (0, 0)

이런 그림이 된다!

 

끝!

이라고 하기에는

이럴 거면 FrameBounds를 굳이 왜 나눈 거야...? 하는 생각이 지워지지 않는다.

Frame으로 위치와 크기를 다 정할 수 있다면, Bounds는 굳이 필요 없지 않나?

 

위 문제는 UIKit: Frame과 Bounds 2에서 다루려고 한다.

 

UIKit: Frame과 Bounds 2

UIKit: Frame과 Bounds 1 UIKit: Frame과 Bounds 1UIKit으로 UI를 그리다 보면 심심찮게 보이는Frame과 Bounds 막상 사용해보면 큰 차이를 못 느낀다...공식 문서를 살펴보면FrameThe frame rectangle,which describes the view’

dev-arthur.tistory.com

 

반응형