iOS 기본 (swift)
[iOS - swift] layoutMargins, UIEdgeInset, contentInset, contentOffset, (여백, 패딩, 마진)
jake-kim
2021. 8. 27. 21:29
스위프트에서의 layoutMagins 개념
- 현재 뷰의 경계와 content와의 여백
- 개념 혼동 주의: 현재 뷰 경계와 superview와의 여백이 아님을 주의
storyboard에서 layoutMargins 확인 방법
- Editor > Canvas >Layout Rectangles

- layout 설정 시 "Constrain to margins" 옵션을 체크한 후 autolayout적용 시 view 내부에 margin값을 고려한 배치

cf) code에서 layoutMarginsGuide 주는 방법: layoutMarginsGuide. 으로 접근
imageView.leadingAnchor.constraint(equalTo: layoutMarginsGuide.leadingAnchor)
- 내부 label이 margin값에 맞추어서 적용된 상황

UIEdgeInsets
- 뷰의 여백 속성 값(top, left, bottom, right)을 갖는 구조체

layoutMargins와 UIEdgeInsets을 이용한 값 설정
- 뷰와 내부 컨텐츠의 left를 30만큼 여백을 주는 방법: layoutMargins 프로퍼티에 UIEdgeInsets 객체 삽입
myView.layoutMargins = UIEdgeInsets(top: 0, left: 30, bottom: 0, right: 0)
| layoutMargins 디폴트 (따로 layoutMargins값 설정 안한 경우) | layoutMargins 수정 |
![]() |
![]() |
- bounds의 inset(by:) 속성: 원래의 view에 파라미터로 들어온 내부 여백을 갖은 경우의 CGRect값 반환

- 예제
/// 뷰의 width 값: 214.0
print(myView.bounds.width)
/// left, right로 각각 내부 여백을 0만큼 준 경우: 214.0 (동일)
let width2 = myView.bounds.inset(by: UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 0)).width
/// left, right로 각각 내부 여백을 각 100만큼 준 경우: 14.0
let width1 = myView.bounds.inset(by: UIEdgeInsets(top: 10, left: 100, bottom: 10, right: 100)).width
- bounds.insetBy(dx:dy:): 원래의 view에 파라미터로 들어온 offset값에따라 변화된 bounds값
let newBounds = myView.bounds.insetBy(dx: 0.0, dy: 12.0)
myView.bounds = newBounds

contentInset vs contentOffset
- contentOffset: 스크롤뷰에서 현재 contentView의 좌표값
- contentInset: 스크롤뷰의 가장자리와 컨텐츠 영역 가장자리 사이의 여백

LayoutMargins
- 개념: view에 컨텐츠를 배치할 때 default로 사용되는 간격

- LayoutMargins 활용
- stackView의 margin값 부여
/// isLayoutMarginsRelativeArrangement: false - 경계를 기준으로 정렬 / true - 레이아웃 여백을 기준으로 정렬
stackView.isLayoutMarginsRelativeArrangement = true
stackView.layoutMargins = UIEdgeInsets(top: 10, left: 30, bottom: 10, right: 30)
| maring값이 없는 디폴트 | margin 부여 |
![]() |
![]() |
* 참고
- https://developer.apple.com/documentation/uikit/uiedgeinsets
- https://developer.apple.com/documentation/coregraphics/cgrect/1624499-inset
- https://developer.apple.com/documentation/uikit/uiedgeinsets
- https://developer.apple.com/documentation/uikit/uiscrollview/1619406-contentinset



