🌟
SwiftUIのNavigationViewを使ってiPadでSplitViewを利用する場合の基本的なコード
SwiftUIのNavigationView
を使ってiPadでSplitViewを利用する場合の基本的となるコードのメモ。
環境
- iOS 14.0+
Code
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
MasterView()
}
}
}
struct MasterView: View {
@State var showingSubView0 = true
@State var showingSubView1 = false
@State var showingSubView2 = false
var body: some View {
VStack {
NavigationLink(destination: SubView0(), isActive: $showingSubView0) {
EmptyView()
}
NavigationLink(destination: SubView1(), isActive: $showingSubView1) {
EmptyView()
}
NavigationLink(destination: SubView2(), isActive: $showingSubView2) {
EmptyView()
}
Button("Navigate1") {
showingSubView1.toggle()
}
Button("Navigate2") {
showingSubView2.toggle()
}
}
.navigationTitle("Master")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Image(systemName: "magnifyingglass")
}
}
}
}
struct SubView0: View {
var body: some View {
Text("SubView0")
.navigationTitle("SubView0")
.navigationBarTitleDisplayMode(.inline)
}
}
struct SubView1: View {
var body: some View {
Text("SubView1")
.navigationTitle("SubView1")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Image(systemName: "person")
}
}
}
}
struct SubView2: View {
var body: some View {
Text("SubView2")
.navigationTitle("SubView2")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Image(systemName: "person.fill")
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
メモ
-
Button
を使ってNavigationLink
の表示切り替えるときはNavigationLink(isActive:)
を使う- labelには
EmptyView()
を指定する
- labelには
@State var showingSubView1 = false
Button("Navigate1") {
showingSubView1.toggle()
}
NavigationLink(destination: SubView1(), isActive: $showingSubView1) {
EmptyView()
}
Discussion