본문 바로가기
Language/Swift

SwiftUI 에서 Overlay, background 이용하기

by IFLA 2022. 12. 23.

 

Overlay

overlay 는 뷰 원본의 공간을 기준으로 그 위에 새로운 뷰를 중첩하여 쌓는 기능을 한다. UiKit 에서 addsSubview 메서드와 같은 기능이다.

 

기본 코드

struct ContentView: View {
	var body: some View {
		Rectangle()
			.fill(Color.red)
			.frame(width: 150.0, height: 150.0)
			.overlay(
				Rectangle()
					.fill(Color.green)
					.offset(x: 10, y: 10))
			)
	}
}

 

실행 화면


Background

뷰 원본의 공간을 기준으로 뷰를 중첩하는 것은 같지만, 위가 아니라 그 아래 방향으로 쌓아 나간다는 점이 다르다.

뷰의 하위 계층에 지정한 색을 가진 또 다른 뷰를 추가하는 기능이다.

 

기본 코드

struct ContentView: View {
    var body: some View {
        Rectangle()
            .fill(Color.red)
            .frame(width: 150, height: 150.0)
            .background(Rectangle()
                .fill(Color.green)
                .offset(x: 20, y: 20)
            )
    }
}

 

실행 화면


개발자 Document

https://developer.apple.com/documentation/swiftui/view/overlay(_:alignment:) 

 

Apple Developer Documentation

 

developer.apple.com

https://developer.apple.com/documentation/swiftui/view/background(_:alignment:) 

 

Apple Developer Documentation

 

developer.apple.com

 

댓글


\