我有一个存储字符串的字典-> bool,在我看来,我将此字典包装在Binding<Bool>
周围,以便能够存储每个NavigationLink
的状态,以便以后能够以编程方式导航。现在,这是第一次工作,第1页->第2页->第3页,但是当您回到第2页时,导航将停止工作。
我检查了isLinkActive
字典的值是否在点击NavigationLink
时正确更新了,但是NavigationLink
没有被激活。
import SwiftUI
class ContentViewModel: ObservableObject {
@Published var isLinkActive:[String: Bool] = [:]
}
struct ContentView: View {
@ObservedObject var contentViewModel = ContentViewModel()
var page3: some View {
Text("Page 3")
}
@State var data = ["1", "2", "3"]
func binding(chatId: String) -> Binding<Bool> {
return .init(get: { () -> Bool in
return self.contentViewModel.isLinkActive[chatId, default: false]
}) { (value) in
self.contentViewModel.isLinkActive[chatId] = value
}
}
var page2: some View {
return
List(data, id: \.self) { data in
NavigationLink(destination: self.page3, isActive: self.binding(chatId: data)) {
Text("Page \(data) Link")
}
}
}
var body: some View {
return NavigationView() {
VStack {
Text("Page 1")
NavigationLink(destination: page2) {
Text("Page 2 Link")
}
}
}
}
}
答案 0 :(得分:1)
您的代码逻辑没有错。唯一的问题是SwiftUI 不会重绘page2
,因为它仅在var body
期间重绘onAppear
,并且该视图不在上下文中。因此,强制刷新的方法是使page2
为主体变量。
struct ContentView: View {
var body: some View {
return NavigationView() {
VStack {
Text("Page 1")
NavigationLink(destination: ContentViewTwo()) {
Text("Page 2 Link")
}
}
}
}
}
struct ContentViewTwo: View {
@ObservedObject var contentViewModel = ContentViewModel()
var page3: some View {
Text("Page 3")
}
@State var data = ["1", "2", "3"]
func binding(chatId: String) -> Binding<Bool> {
return .init(get: { () -> Bool in
return self.contentViewModel.isLinkActive[chatId, default: false]
}) { (value) in
self.contentViewModel.isLinkActive[chatId] = value
}
}
var body: some View {
return
List(data, id: \.self) { data in
NavigationLink(destination: self.page3, isActive: self.binding(chatId: data)) {
Text("Page \(data) Link")
}
}
}
}