🌟

SwiftUIのNavigationViewを使ってiPadでSplitViewを利用する場合の基本的なコード

2021/04/09に公開

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()を指定する
@State var showingSubView1 = false

Button("Navigate1") {
    showingSubView1.toggle()
}

NavigationLink(destination: SubView1(), isActive: $showingSubView1) {
    EmptyView()
}

Discussion