본문 바로가기
Language/Swift

SwiftUI를 이용한 탭 메뉴 만들기 (TabView)

by IFLA 2022. 11. 26.

상단의 메뉴바를 이용하여 화면이 전환되게 하는 View를 SwiftUI 에서는 TabView 를 제공한다.

 

기본 코드

struct FirstView: View {
	var body: some View {
		VStack {
			Text("First View")
		}
	}
}

struct SecondView: View {
	var body: some View {
		VStack {
			Text("Second View")
		}
	}
}

struct ContentView: View {
	var body: some View {
		TabView {
			FirstView()
				.tabItem {
					Image(systemName: "house")
					Text("Home")
				}

			SecondView()
				.tabItem {
					Image(systemName: "person")
					Text("User")
			}
		}
	}
}

 

실행화면

 

프로그래밍 방식으로 탭 간 전환

  • 탭 바를 터치하여 탭 간 전환을 한다. 하지만 프로그래밍 방식으로 버튼을 생성해 특정 탭으로 전환할 수 있다.
struct ContentView: View {
	@State private var selection = 0

	var body: some View {
		ZStack(alignment: .topTrailing) {
			TabView(selection: $selection) {
				...
			}
			.onAppear() {
				UITabBar.appearance().barTintColor = .white
			}
			
			Button(action : {
          selection = (selection + 1) % 3
      }) {
          Text("다음")
              .font(.system(.headline))
              .padding()
              .foregroundColor(.white)
              .background(Color.blue)
              .cornerRadius(10)
              .padding()
      }
		}
	}
}

 

TabViewStyle

  • .tabViewStyle() 수정자를 TabView에 연결하고 PageTabViewStyle()을 전달해야 한다.
  • .indexViewStyle(PageIndexViewStyle(backgroundDisplayMode: .always))

 

개발자 Document

https://developer.apple.com/documentation/swiftui/tabview

 

Apple Developer Documentation

 

developer.apple.com

 

댓글


\