ios - 程序化导航 SwiftUI:重新选择和选择屏幕外链接的问题
问题描述
我无法NavigationLink
在 SwiftUI 中使用编程导航,特别是有两个关键问题:
- Changing selection when selection is not nil (ie re-selecting after a
NavigationLink
is already selected) - 尝试选择屏幕外
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")
}
}
解决方案
推荐阅读
- python - pandas 导入带有 '"' 和 ',' 的 csvs 作为 csv 中的值
- sql - 将 2 条记录解析为一条并连接表
- ios - firebase 不总是通过 APNs 发送通知吗?
- json - 使用 JSON 格式化 Sharepoint 列表日期或选择列
- codenameone - 带有侧边菜单的工具栏搜索
- java - 在类路径中找不到“qtjambi-deployment.xml”,通过“java.library.path”加载库
- postgresql - 如何将 Duration 类型映射到 Interval?
- ios - 用于将 Single<[Element]> 转换为 Observable 的 rxSwift 扩展
- doctrine-orm - API 平台 - PATCH 和 ArrayCollection
- maven - Maven:如何防止 exec 插件显示其堆栈跟踪?