NavigationLink Works Only for Once - ios

I was working on an application with login and after login there are categories listed. And under each category there are some items listed horizontally. The thing is after login, main page appears and everything is listed great. When you click on an item it goes to detailed screen but when you try to go back it just crashes. I found this flow Why does my SwiftUI app crash when navigating backwards after placing a `NavigationLink` inside of a `navigationBarItems` in a `NavigationView`? but i could not solve my problem. Since my project become complicated, I just wanted to practice navigation in swiftui and I created a new project. By the way I downloaded the latest xcode version 11.3. I wrote a simple code as follows:
NavigationView{
NavigationLink(destination: Test()) {
Text("Show Detail View")
}
.navigationBarTitle("title1")
And Test() view is as follows:
import SwiftUI
struct Test: View {
var body: some View {
Text("Hello, World!")
}
}
struct Test_Previews: PreviewProvider {
static var previews: some View {
Test()
}
}
As you can see it is really simple. I also tried similar examples on the internet but it does not work the way it suppose to work. When I run the project, I click the navigation link and it navigates to Test() view. Then I click back button and it navigates to the main page. However, when I click the navigation link second time, nothing happens. Navigation link works only once and after that nothing happens. It does not navigate, it des not throw any error. I am new to swiftui and everything is great but the navigation. I tried many examples and suggested solutions on the internet, but nothing seems to fix my issues.

[UPDATE] Nov 5, 2020 - pawello2222 says that this issue has been fixed in Xcode 12.1.
[UPDATE] Jun 14, 2020 - Quang Hà says that this issue has come back in Xcode 11.5.
[UPDATE] Feb 12, 2020 - I checked for this issue in Xcode 11.4 beta and found that this issue has been resolved.
I was getting the same issue in my project too, when I was testing it in Xcode's simulator. However, when I launched the app on a real device (iPhone X with iOS 13.3), NavigationLink was working totally fine. So, it really does seem like Xcode's bug.

Simulator 11.4: This issue has been fixed
You need to reset the default isActive value in the second view.
It works on devices and emulators.
struct NavigationViewDemo: View {
#State var isActive = false
var body: some View {
NavigationView {
VStack {
Text("View1")
NavigationLink(
destination: NavigationViewDemo_View2(isActive: $isActive),
isActive: $isActive,
label: { Button(action: { self.isActive = true }, label: { Text("click") }) })
}
}
}
}
struct NavigationViewDemo_View2: View {
#Binding var isActive: Bool
var body: some View {
Text("View2")
.navigationBarItems(leading: Button(action: { self.isActive = false }, label: { Text("Back") }))
}
}

Presumably this will be resolved when Apple fixes the related bug that prevents 13.3 from being selectable as a deployment target.
I'm experiencing the same issue as everyone else. This issue is present in simulator and preview running 13.2, but is fixed when deploying to my own device running 13.3.

As #Александр Грабовский said its seems like a Xcode 11.3 bug, I am encountering the same problem, you must downgrade or use some workaround like custom back button as below
struct ContentView: View {
#State private var pushed: Bool = false
var body: some View {
NavigationView {
VStack {
Button("Show Detail View") {
self.pushed.toggle()
}
NavigationLink(destination: Test(pushed: $pushed), isActive: $pushed) { EmptyView() }
}.navigationBarTitle("title1")
}
}
}
struct Test: View {
#Binding var pushed: Bool
var body: some View {
Text("Hello, World!")
.navigationBarBackButtonHidden(true)
.navigationBarItems(leading: BackButton(label: "Back") {
self.pushed = false
})
}
}
struct BackButton: View {
let label: String
let closure: () -> ()
var body: some View {
Button(action: { self.closure() }) {
HStack {
Image(systemName: "chevron.left")
Text(label)
}
}
}
}

For anyone who's having the same symptom with other versions of iOS than the buggy beta identified by other answers, there's another reason you might be seeing this behaviour.
If your NavigationLink is nested inside another NavigationLink, the inner NavigationLink will only work once, unless you add isDetailLink(false) to the outer link.

Related

SwiftUI View with StateObject, a Form element and a ForEach breaks bindings when trying to use NavigationLink Inside the form

OK something weird is going on and I want to see if anyone else have this issue.
Consider the following ViewModel class with one published property to use from a View:
final class ViewModel: ObservableObject {
#Published var isActive = false
}
When using this view:
struct MainView: View {
#StateObject var viewModel = ViewModel()
var body: some View {
NavigationView {
Form {
NavigationLink (
destination: ChildView(isActive: $viewModel.isActive),
isActive: $viewModel.isActive,
label: { Text("Go to child view") }
)
// Adding this ForEach causes the NavigationLink above to have a broken binding
ForEach(1..<4) {
Text("\($0)")
}
}
.navigationBarTitle("Test")
}
}
}
And this SubView:
struct ChildView: View {
#Binding var isActive: Bool
var body: some View {
Button("Go back", action: { isActive = false })
}
}
The issue
The expected result is when tapping on "Go to child view", navigating to the subview and tapping "Go back" to return to the main view - it should navigate back using the isActive binding.
But actually, the button "Go Back" Doesn't work.
BUT If I remove the ForEach element from the form in the main view, the button works again. And it looks like the ForEach breaks everything.
Additional findings:
Changing Form to VStack fixes the issue
Using a struct and a #State also fixes the issue
Extracting the ForEach to a subview fixes the issue but as soon as I pass the viewmodel or part of it to the subview as a binding or as a ObservedObject - it still broken
Can anything advise if there is a logical issue with the code or is it a SwiftUI bug?
Any suggestions for a workaround?
Video of the expected behavior:
https://i.stack.imgur.com/BaggK.gif
Apple developer forum discussion: https://developer.apple.com/forums/thread/674127
Update
It looks like the issue has been fixed in the latest iOS 14.5 Beta 2 🎉
The issue has been fixed on iOS 14.5

SwiftUI NavigationLink Text click not working [duplicate]

I was working on an application with login and after login there are categories listed. And under each category there are some items listed horizontally. The thing is after login, main page appears and everything is listed great. When you click on an item it goes to detailed screen but when you try to go back it just crashes. I found this flow Why does my SwiftUI app crash when navigating backwards after placing a `NavigationLink` inside of a `navigationBarItems` in a `NavigationView`? but i could not solve my problem. Since my project become complicated, I just wanted to practice navigation in swiftui and I created a new project. By the way I downloaded the latest xcode version 11.3. I wrote a simple code as follows:
NavigationView{
NavigationLink(destination: Test()) {
Text("Show Detail View")
}
.navigationBarTitle("title1")
And Test() view is as follows:
import SwiftUI
struct Test: View {
var body: some View {
Text("Hello, World!")
}
}
struct Test_Previews: PreviewProvider {
static var previews: some View {
Test()
}
}
As you can see it is really simple. I also tried similar examples on the internet but it does not work the way it suppose to work. When I run the project, I click the navigation link and it navigates to Test() view. Then I click back button and it navigates to the main page. However, when I click the navigation link second time, nothing happens. Navigation link works only once and after that nothing happens. It does not navigate, it des not throw any error. I am new to swiftui and everything is great but the navigation. I tried many examples and suggested solutions on the internet, but nothing seems to fix my issues.
[UPDATE] Nov 5, 2020 - pawello2222 says that this issue has been fixed in Xcode 12.1.
[UPDATE] Jun 14, 2020 - Quang Hà says that this issue has come back in Xcode 11.5.
[UPDATE] Feb 12, 2020 - I checked for this issue in Xcode 11.4 beta and found that this issue has been resolved.
I was getting the same issue in my project too, when I was testing it in Xcode's simulator. However, when I launched the app on a real device (iPhone X with iOS 13.3), NavigationLink was working totally fine. So, it really does seem like Xcode's bug.
Simulator 11.4: This issue has been fixed
You need to reset the default isActive value in the second view.
It works on devices and emulators.
struct NavigationViewDemo: View {
#State var isActive = false
var body: some View {
NavigationView {
VStack {
Text("View1")
NavigationLink(
destination: NavigationViewDemo_View2(isActive: $isActive),
isActive: $isActive,
label: { Button(action: { self.isActive = true }, label: { Text("click") }) })
}
}
}
}
struct NavigationViewDemo_View2: View {
#Binding var isActive: Bool
var body: some View {
Text("View2")
.navigationBarItems(leading: Button(action: { self.isActive = false }, label: { Text("Back") }))
}
}
Presumably this will be resolved when Apple fixes the related bug that prevents 13.3 from being selectable as a deployment target.
I'm experiencing the same issue as everyone else. This issue is present in simulator and preview running 13.2, but is fixed when deploying to my own device running 13.3.
As #Александр Грабовский said its seems like a Xcode 11.3 bug, I am encountering the same problem, you must downgrade or use some workaround like custom back button as below
struct ContentView: View {
#State private var pushed: Bool = false
var body: some View {
NavigationView {
VStack {
Button("Show Detail View") {
self.pushed.toggle()
}
NavigationLink(destination: Test(pushed: $pushed), isActive: $pushed) { EmptyView() }
}.navigationBarTitle("title1")
}
}
}
struct Test: View {
#Binding var pushed: Bool
var body: some View {
Text("Hello, World!")
.navigationBarBackButtonHidden(true)
.navigationBarItems(leading: BackButton(label: "Back") {
self.pushed = false
})
}
}
struct BackButton: View {
let label: String
let closure: () -> ()
var body: some View {
Button(action: { self.closure() }) {
HStack {
Image(systemName: "chevron.left")
Text(label)
}
}
}
}
For anyone who's having the same symptom with other versions of iOS than the buggy beta identified by other answers, there's another reason you might be seeing this behaviour.
If your NavigationLink is nested inside another NavigationLink, the inner NavigationLink will only work once, unless you add isDetailLink(false) to the outer link.

How do I reset a selection tag when pushing a NavigationLink programmatically?

I want to push a view programmatically instead of relying on the interface that NavigationLink provides (e.g. I want to use a button with no chevron). The correct way is to use NavigationLink with tag and selection, and an EmptyView.
When I attempt to use the following code to push a view, it works to push the view the first time:
struct PushExample: View {
#State private var pushedView: Int? = nil
var body: some View {
NavigationView {
VStack {
Form {
Button(action: { self.pushedView = 1 }) { Text("Push view") }
}
NavigationLink(destination: Text("Detail view"), tag: 1, selection: $pushedView) { EmptyView() }
}
}
}
}
However, if I tap the back button on the view, and try hitting the button again, it no longer pushes the view. This is because the value pushedView is being set to 1 again, but it is already at 1. Nothing is resetting it back to nil upon pop of the Detail view.
How do I get subsequent taps of the button to push the view again?
TL;DR: There is no need to reset the state variable, as SwiftUI will automatically handle it for you. If it's not, it may be a bug with the simulator.
This was a simulator bug on Xcode 11.3!
The way to check if it's a simulator bug is to run an even simpler example:
struct ContentView: View {
var body: some View {
NavigationView {
NavigationLink("Push", destination: Text("Detail"))
}
}
}
On the Xcode 11.3 iPhone 11 Pro Max, this would only work the first time you tap the link.
This worked fine on both a 13.2 and a 13.3 device.
Therefore, when running into odd SwiftUI issues, test on device rather than the simulator.
Update: Restarting the computer didn't fix it either. Thus while SwiftUI is still new, may be better off to use a real device for testing rather than the simulator.

Why is SwiftUI picker in form repositioning after navigation?

After clicking the picker it navigates to the select view. The item list is rendered too far from the top, but snaps up after the animation is finished. Why is this happening?
Demo: https://gfycat.com/idioticdizzyazurevase
I already created a minimal example to rule out navigation bar titles and buttons, form sections and other details:
import SwiftUI
struct NewProjectView: View {
#State var name = ""
var body: some View {
NavigationView {
Form {
Picker("Client", selection: $name) {
Text("Client 1")
Text("Client 2")
}
}
}
}
}
struct NewProjectView_Previews: PreviewProvider {
static var previews: some View {
NewProjectView()
}
}
This happens in preview mode, simulator and on device (Xcode 11.2, iOS 13.2 in simulator, 13.3 beta 1 on device).
The obviously buggy behavior can be worked around when forcing the navigation view style to stacked:
NavigationView {
…
}.navigationViewStyle(StackNavigationViewStyle())
This is a solution to my problem, but I won‘t mark this as accepted answer (yet).
It seems to be a bug, even if it may be triggered by special circumstances.
My solution won‘t work if you need another navigation view style.
Additionally, it won‘t fix the horizontal repositioning mentioned by DogCoffee in the comments.
In my opinion, it has something to do with the navigation bar. In default (no mention of .navigationBarTitle extension), the navigation display mode is set to .automatic, this should be amend to .inline. I came across another post similar to this and use their solution to combine with yours, by using .navigationBarTitle("", displayMode: .inline) should help.
import SwiftUI
struct NewProjectView: View {
#State var name = ""
var body: some View {
NavigationView {
Form {
Picker("Client", selection: $name) {
Text("Client 1")
Text("Client 2")
}
}
.navigationBarTitle("", displayMode: .inline)
}
}
}
struct NewProjectView_Previews: PreviewProvider {
static var previews: some View {
NewProjectView()
}
}
Until this bug is resolved another way to work around this issue while retaining the DoubleColumnNavigationViewStyle for iPads would be to conditionally set that style:
let navView = NavigationView {
…
}
if UIDevice.current.userInterfaceIdiom == .pad {
return AnyView(navView.navigationViewStyle(DoubleColumnNavigationViewStyle()))
} else {
return AnyView(navView.navigationViewStyle(StackNavigationViewStyle()))
}
Thanks for this thread everyone! Really helped me understand things more and get a hold of one of my problems. To share with others, I was having this problem to but I was also having this problem when I set a section to appear in a if/else statement set on a section with a toggle. When the toggle was activated it would shift the section header horizontally a few pixels.
The following is how I fixed it
Section(header: Text("Subject Identified").listRowInsets(EdgeInsets()).padding(.leading)) {
Picker(selection: $subIndex, label: Text("Test")) {
ForEach(0 ..< subIdentified.count) {
Text(self.subIdentified[$0]).tag($0)
}
}
.labelsHidden()
.pickerStyle(SegmentedPickerStyle())
I'm still having horizontal shift on my picker selection view and not sure how to fix. I created another thread to received input. Thanks again! SwiftUI Shift Picker Text Horizontal

SwiftUI: NavigationDestinationLink deprecated

After installing Xcode 11 beta 5 this morning, I noticed that NavigationDestinationLink was deprecated in favor of NavigationLink.
Also, that's what Apple says about it in the release notes:
NavigationDestinationLink and DynamicNavigationDestinationLink are deprecated; their functionality is now included in NavigationLink. (50630794)
The way I use NavigationDestinationLink is to programmatically push a new view into the stack via self.link.presented?.value = true. That functionality doesn't seem to be present in NavigationLink.
Any idea anyone?
I would rather not use NavigationDestinationLink anymore as it's deprecated...
Thank you!
UPDATE:
Actually, the NavigationDestinationLink way does not work anymore so I guess we have no way of pushing programmatically anymore?
UPDATE 2:
NavigationLink(destination: CustomView(), isActive: $isActive) {
return Text("")
}
This works but when you pass isActive to true, any state update will trigger this code and push over and over... Also, if you pass it back to false, it will pop the view.
Not only updates, if you set isActive to true, it will push the view (good) and if we press the back button, it will go back then immediately push again since it's still true.
Playing with onAppear was my hope but it's not called when going back to it...
I'm not sure how we're supposed to use this.
After spending some time with NavigationLink(destination:isActive), I am liking it a lot more than the old NavigationDestinationLink. The old view was a little confusing, while the new approach seems much more elegant. And once I figure out how to push without animations, it would make state restoration at application launch very easy.
There is one problem though, a big and ugly bug. :-(
Pushing a view programatically works fine, and popping it programatically does too. The problem starts when we use the BACK button in the pushed view which behaves oddly every other time. The first time the view is popped, the view pops and pushes again immediately. The second time around it works fine. Then the third time it starts all over again.
I have created a bug report (number here). I recommend you do the same and reference my number too, to help Apple group them together and get more attention to the problem.
I designed a workaround, that basically consists of replacing the default Back button, with our own:
class Model: ObservableObject {
#Published var pushed = false
}
struct ContentView: View {
#EnvironmentObject var model: Model
var body: some View {
NavigationView {
VStack {
Button("Push") {
// view pushed programmatically
self.model.pushed = true
}
NavigationLink(destination: DetailView(), isActive: $model.pushed) { EmptyView() }
}
}
}
}
struct DetailView: View {
#EnvironmentObject var model: Model
var body: some View {
Button("Bring me Back (programatically)") {
// view popped programmatically
self.model.pushed = false
}
// workaround
.navigationBarBackButtonHidden(true) // not needed, but just in case
.navigationBarItems(leading: MyBackButton(label: "Back!") {
self.model.pushed = false
})
}
}
struct MyBackButton: View {
let label: String
let closure: () -> ()
var body: some View {
Button(action: { self.closure() }) {
HStack {
Image(systemName: "chevron.left")
Text(label)
}
}
}
}
To improve the workaround without replacing the back button with a custom one, you can use the code above :
NavigationLink(destination: Test().onAppear(perform: {
self.editPushed = nil
}), tag: 1, selection: self.$editPushed) {
Button(action: {
self.editPushed = 1
}) {
Image(systemName: "plus.app.fill")
.font(.title)
}
}
The onAppear block will erase the selection value preventing to display the detail view twice
You can also use NavigationLink(destination:tag:selection)
NavigationLink(destination: MyModal(), tag: 1, selection: $tag) {
EmptyView()
}
So programmatically you can set tag to 1 in order to push MyModal. This approach has the same behaviour as the one with the Bool binding variable, so when you pop the first time it pushes the view immediately, hopefully they'll fix it in next beta.
The only downside I see with this approach, compared to DynamicNavigationDestinationLink is that you need to provide a View to NavigationLink, even if you don't need one. Hopefully they'll find a cleaner way to allow us to push programmatically.
The solution is to create custom back button for your detail view and pop detail view manually.
.navigationBarItems(leading:
Button(action: {
self.showDetail = false
}) {
Image(systemName: "chevron.left").foregroundColor(.red)
.font(.system(size: 24, weight: .semibold))
Text("Back").foregroundColor(.red)
.font(.system(size: 19))
}
)
The method used in the selected answer has been deprecated again. Here's the solution copied from this answer in this post.
#State private var readyToNavigate : Bool = false
var body: some View {
NavigationStack {
VStack {
Button {
//Code here before changing the bool value
readyToNavigate = true
} label: {
Text("Navigate Button")
}
}
.navigationTitle("Navigation")
.navigationDestination(isPresented: $readyToNavigate) {
MyTargetView()
}
}
}

Resources