LoginSignup
0
1

More than 1 year has passed since last update.

【SwiftUI】NavigationView の中の TabView の中の NavigationLink 先で Sheet を開くと NavigationLink が勝手に戻るバグの対処法

Last updated at Posted at 2022-01-08

GIFの様に、 SecondView で Sheet を開くと FirstView に戻ってしまいます。

解消法は、 NavigationViewTabViewTabViewNavigationView に変えればOKです。

20220108_01.gif

import SwiftUI

struct FirstView: View {

    @State var selection = 0

    var body: some View {

        // NG。勝手に戻る。
//        NavigationView {
//            TabView(selection: $selection) {
        // OK。
        TabView(selection: $selection) {
            NavigationView {
                NavigationLink(destination: SecondView()) {
                    Text("Go to SecondView").font(.title)
                }
                .tag(0)
            }
            .navigationTitle("FirstView")
        }
    }
}

struct SecondView: View {

    @State var isPresented = false

    var body: some View {
        Button(action: { isPresented = true }) {
            Text("open sheet").font(.title)
        }
        .sheet(isPresented: $isPresented) {
            Text("sheet").font(.title)
        }
        .navigationTitle("SecondView")
    }
}

struct FirstView_Previews: PreviewProvider {
    static var previews: some View {
        FirstView()
    }
}

バージョン
Xcode 13.1
iOS 15.0

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1