简体   繁体   中英

SwiftUI Popover Disappears When It's Inside a NavigationView

I have a popover inside of a NavigationView:

import SwiftUI

struct ContentView: View {
  var body: some View {
    NavigationView {
      NavigationLink(destination: ChildView()) {
        Text("Navigate")
      }
    }
    .navigationViewStyle(StackNavigationViewStyle())
  }
}

struct ChildView: View {
  @State private var popover = false

  var body: some View {
    HStack {
      Button(action: { self.popover = true }) {
        Text("Toggle")
      }
      .popover(isPresented: $popover) {
        Text("Yolo")
      }
    }
  }
}

When you toggle the popover for the first time after starting the app, it immediately disappears. After that it works correctly. Is this a bug in NavigationView? Are there any workarounds?

Use sheet instead:

struct ContentView: View {
    var body: some View {
        NavigationView {
            NavigationLink(
                destination: ChildView()
            ) {
                Text("Navigate")
            }
        }
    }
}

struct ChildView: View {
    @State
    private var isPresented = false
    var body: some View {
        HStack {
            Button(
                action: {
                    isPresented.toggle()
                }) {
                Text("Present")
            }
        }
        .sheet(
            isPresented: $isPresented
        ) {
            Text("Yolo")
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM