SwiftUI에서 탭 뷰 만들기
SwiftUI 탭 뷰 개요
TabView 컴포넌트 : 탭 바에 있는 탭 아이템을 사용자가 선택할 때 여러 하위 뷰들 사이의 이동
- TabView 컨테이너 뷰를 사용
- 탭 아이템을 가진 탭 바를 레이아웃 하단에 표시
- 탭 아이템은 수정자를 사용(
.tabItem {}
)- Text 뷰와 Image 뷰로 구성, 다른 타입x
- 태그를 추가하여 선택된 탭 제어 가능
TabView 컨테이너 추가하기
var body: some View {
TabView {
Text("First Content View")
Text("Second Content View")
Text("Third Content View")
}
.font(.largeTitle)
}
첫 번째 콘텐트 뷰와 탭 바가 화면 하단에 표시
아직 탭 아이템을 추가하지 않았기 때문에 탭 바가 비어있음
- iOS15부터 탭 바와 내비게이션바의 구분선이 없어짐
<설정방법>
TabView { . . } .onAppear() { UITabBar.appearance().scrollEdgeAppearance = .init() }
탭 아이템 추가하기
tabItem() 수정자를 사용하여 각 콘텐트 뷰에 탭 아이템을 적용
TabView {
Text("First Content View")
.tabItem {
Image(systemName: "1.circle")
Text("Screen One")
}
Text("Second Content View")
.tabItem {
Image(systemName: "2.circle")
Text("Screen Two")
}
Text("Third Content View")
.tabItem {
Image(systemName: "3.circle")
Text("Scren Three")
}
}
.font(.largeTitle)
탭 아이템 태그 추가하기
코드로 현재 선택된 탭을 제어하려면 태그가 각 탭 아이템에 추가
struct ContentView: View {
@State private var selection = 1 // 상태 프로퍼티
var body: some View {
TabView(selection: $selection) { // 바인딩
Text("First Content View")
.tabItem {
Image(systemName: "1.circle")
Text("Screen One")
}.tag(1)
Text("Second Content View")
.tabItem {
Image(systemName: "2.circle")
Text("Screen Two")
}.tag(2)
Text("Third Content View")
.tabItem {
Image(systemName: "3.circle")
Text("Scren Three")
}.tag(3)
}
.font(.largeTitle)
}
}
selection 상태 프로퍼티를 태그 범위 내의 다른 값으로 변경하면 해당 콘텐트 뷰로 전환
응용
- ContentView 꾸미기
var body: some View { TabView(selection: $selection) { firstView() .tabItem { Image(systemName: "1.circle") Text("Screen One") }.tag(1) . . } } struct firstView: View { var body: some View { VStack { Text("First Content View") Image(systemName: "star.fill") } } }
- tag를 이용한 Next 버튼 추가
var body: some View { ZStack (alignment: .topTrailing) { TabView(selection: $selection) { firstView() .tabItem { Image(systemName: "1.circle") Text("Screen One") }.tag(0) Text("Second Content View") .tabItem { Image(systemName: "2.circle") Text("Screen Two") }.tag(1) Text("Third Content View") .tabItem { Image(systemName: "3.circle") Text("Scren Three") }.tag(2) } .font(.largeTitle) .onAppear() { UITabBar.appearance().scrollEdgeAppearance = .init() } Button(action: { selection = (selection + 1) % 3 }) { Text("Next") .font(.system(.headline, design: .rounded)) .padding() .foregroundColor(.white) .background(Color.blue) .cornerRadius(10.0) .padding() } } }