Why does my SwiftUI app crash when navigating backwards after placing a `NavigationLink` inside of a `navigationBarItems` in a `NavigationView`?

后端 未结 9 1153
轮回少年
轮回少年 2020-12-04 12:25

EDIT: This has been fixed in iOS 13.3!

Minimal reproducible example (Xcode 11.2 beta, this works in Xcode 11.1):

struct Parent: View {         


        
9条回答
  •  南笙
    南笙 (楼主)
    2020-12-04 12:56

    As a workaround, based on Chuck H's answer above, I've encapsulated the NavigationLink as a hidden element:

    struct HiddenNavigationLink: View {
    var destination: Content
    @Binding var activateLink: Bool
    
    var body: some View {
        NavigationLink(destination: destination, isActive: self.$activateLink) {
            EmptyView()
        }
        .frame(width: 0, height: 0)
        .disabled(true)
        .hidden()
    }
    }
    

    Then you can use it within a NavigationView (which is crucial) and trigger it from a Button in a nav bar:

    VStack {
        HiddenNavigationList(destination: SearchView(), activateLink: self.$searchActivated)
        ...
    }
    .navigationBarItems(trailing: 
        Button("Search") { self.searchActivated = true }
    )
    

    Wrap this in "//HACK" comments so when Apple fixes this you can replace it.

提交回复
热议问题