问题
I want to programmatically be able to navigate to a link within a List
of NavigationLinks
when the view appears (building deep linking from push notification). I have a string -> Bool dictionary which is bound to a custom Binding<Bool>
inside my view. When the view appears, I set the bool property, navigation happens, however, it immediately pops back. I followed the answer in SwiftUI NavigationLink immediately navigates back and made sure that each item in the List
has a unique identifier, but the issue still persists.
Two questions:
- Is my binding logic here correct?
- How come the view pops back immediately?
import SwiftUI
class ContentViewModel: ObservableObject {
@Published var isLinkActive:[String: Bool] = [:]
}
struct ContentViewTwo: View {
@ObservedObject var contentViewModel = ContentViewModel()
@State var data = ["1", "2", "3"]
@State var shouldPushPage3: Bool = true
var page3: some View {
Text("Page 3")
.onAppear() {
print("Page 3 Appeared!")
}
}
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 3 Link with Data: \(data)")
}.onAppear() {
print("link appeared")
}
}.onAppear() {
print ("ContentViewTwo Appeared")
if (self.shouldPushPage3) {
self.shouldPushPage3 = false
self.contentViewModel.isLinkActive["3"] = true
print("Activating link to page 3")
}
}
}
}
struct ContentView: View {
var body: some View {
return NavigationView() {
VStack {
Text("Page 1")
NavigationLink(destination: ContentViewTwo()) {
Text("Page 2 Link")
}
}
}
}
}
回答1:
The error is due to the lifecycle of the ViewModel, and is a limitation with SwiftUI NavigationLink itself at the moment, will have to wait to see if Apple updates the pending issues in the next release.
来源:https://stackoverflow.com/questions/62275502/swiftui-navigationlink-programmatic-navigation-inside-onappear-immediately-navig