← 아카이브로 돌아가기

Development · SwiftUI

background와 overlay의 레이아웃 차이

기준 뷰의 뒤와 앞에 콘텐츠를 배치하는 background와 overlay의 크기·정렬 방식을 비교합니다.

Velog 원문 보기 ↗

Development 아카이브 표지

기준 뷰 뒤에 색을 놓는 것과 앞에 배지를 올리는 것은 비슷해 보여도 크기를 결정하는 순서가 다르다. background와 overlay를 겹쳐 보며 그 차이를 확인했다.

Backgrounds

뷰 뒷면에 다양한 요소들을 추가할 수 있다.

Text("Hello, World!")
	.background(
    	Color.red // 색상 추가
        LinearGradient(
        gradient: Gradient(colors: [Color.red, Color.blue]),
        startPoint: .leading,
        endPoint: .trailing
        ) // 그라디언트 추가
        Circle() // 도형 추가
    )

여러개를 복수로 추가할 수 있다.(Overlays도 동일)

Text("Hello, World!")
	.background(
        Circle()
        	.fill(
            	LinearGradient(
        		gradient: Gradient(colors: [Color.red, Color.blue]),
        		startPoint: .leading,
        		endPoint: .trailing
				)
			)
            .frame(width: 100, height: 100, alignment: .center)
	)
    .background(
        Circle()
        	.fill(
            	LinearGradient(
        		gradient: Gradient(colors: [Color.blue, Color.red]),
        		startPoint: .leading,
        		endPoint: .trailing
				)
			)
            .frame(width: 120, height: 120, alignment: .center)
	)

Overlays

뷰 앞면에 다양한 요소들을 추가할 수 있다.

Circle()
	.fill(Color.pink)
    .frame(width: 100, height: 100)
    .overlay(
    	Text("A") // 텍스트 추가
        	.font(.largeTitle)
            .foregroundColor(.white)
		Circle() // 도형 추가
    )

Overlay안의 뷰에 Overlay를 추가할 수 있다.(Backgrounds도 동일) 뷰를 기준으로 Overlay를 정렬할 수 있다.(Backgrounds도 동일)

Circle()
	.frame(width: 100, height: 100)
	.foregroundColor(.red)
	.overlay( // 첫 번째 Overlay
		Circle()
			.frame(width: 40, height: 40)
			.overlay ( // 두 번째 Overlay
				Text("1")
					.foregroundColor(.white)
			)
		, alignment: .bottomTrailing) // 뷰 기준 정렬
← 아카이브로 돌아가기