首页 > 解决方案 > 程序化导航 SwiftUI:重新选择和选择屏幕外链接的问题

问题描述

我无法NavigationLink在 SwiftUI 中使用编程导航,特别是有两个关键问题:

  1. Changing selection when selection is not nil (ie re-selecting after a NavigationLinkis already selected)
  2. 尝试选择屏幕外NavigationLink

下面我包含了一个简化我的情况的示例项目:

import SwiftUI

@main
struct Programatic_NavigationApp: App {
    
    @StateObject var appState = AppState()
    
    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(appState)
        }
    }
}


//Shared AppSate to hold selection values
final class AppState: ObservableObject {
    
    @Published var selectedNavItem: Int? = nil
    @Published var tabSelection: TabItem = .list
    
}

enum TabItem {
    case search
    case list
}

struct ContentView: View {
    
    @EnvironmentObject var appState: AppState
    
    var body: some View {
        TabView(selection: $appState.tabSelection){
            NavigationView{
                ListView()
            }
            .tabItem { Label("List", systemImage: "list.dash") }
            .tag(TabItem.list)
            NavigationView{
                SearchView()
            }
            .tabItem { Label("Search", systemImage: "magnifyingglass") }
            .tag(TabItem.search)
        }
    }
}

struct ListView: View {
    
    @EnvironmentObject var appState: AppState
    
    var body: some View {
        List{
            ForEach(1..<100) { navItem in
                NavigationLink(
                    destination: Text("This is nav item \(navItem)"),
                    tag: navItem,
                    selection: $appState.selectedNavItem,
                    label: {Text("Navigate to \(navItem)")})
            }
        }
        .navigationTitle("Navigation List")
    }
}

struct SearchView: View {
    
    @EnvironmentObject var appState: AppState
    
    var body: some View {
        VStack(spacing: 20){
            Button(action: {
                appState.tabSelection = .list
                appState.selectedNavItem = 1
            }, label: {
                Text("Navigate to item 1")
            })
            
            Button(action: {
                appState.tabSelection = .list
                appState.selectedNavItem = 5
                
            }, label: {
                Text("Navigate to item 5")
            })
            
            Button(action: {
                appState.tabSelection = .list
                appState.selectedNavItem = 25
                
            }, label: {
                Text("Navigate to item 25")
            })
            
            Button(action: {
                appState.tabSelection = .list
                appState.selectedNavItem = 75
                
            }, label: {
                Text("Navigate to item 75")
            })
        }
        .navigationTitle("Search")
    }
}


标签: iosswiftswiftui

解决方案


推荐阅读