Output print statements

Hi all,

I am unsure as to why my print statements aren't being shown in the output section when I run a simulation ?

Please could you have a look at my code and explain ?

import SwiftUI

struct ContentView: View { @State var dateIdentifier : String = "" @State var lastSelectedIdentifier : String = "" var body: some View { NavigationView { VStack { Button(action: { dateIdentifier.append("a"); lastSelectedIdentifier.append("a"); print(dateIdentifier);

            }) {
                NavigationLink(destination: Text("OutPut")) {
                    Rectangle()
                        .frame(width: 100, height: 100)
                        
                }
            }

            Button(action: {
                dateIdentifier.append("b");
                lastSelectedIdentifier.append("b");
                print(dateIdentifier);
            }) {
                NavigationLink(destination: Text("OutPut")) {
                    Rectangle()
                        .frame(width: 100, height: 100)
                }
            }

            Button(action: {
                dateIdentifier.append("c");
                lastSelectedIdentifier.append("c");
                print(dateIdentifier);
            }) {
                NavigationLink(destination: Text("OutPut")) {
                    Rectangle()
                        .frame(width: 100, height: 100)
                }
            }
        }
    }
}

}

Thank you

Connor

Problem

  • NavigationLink and Button both perform actions.
  • So having both NavigationLink and Button doesn't make sense, so the action of the button is ignored.

Points to note

  • NavigationLink is used for navigation
  • NavigationView is deprecated, so use NavigationStack instead

Solution

  • Given below is sample code using NavigationStack, use onChange(of:) to detect any changes to path.

Tip

  • You could even pass the path variable as a binding to the destination views
struct ContentView: View {
    @State private var path = [Int]()
    
    var body: some View {
        NavigationStack(path: $path) {
            VStack {
                NavigationLink(value: 1) {
                    Rectangle()
                        .frame(width: 100, height: 100)
                }
                
                NavigationLink(value: 2) {
                    Rectangle()
                        .frame(width: 100, height: 100)
                }
                
                NavigationLink(value: 3) {
                    Rectangle()
                        .frame(width: 100, height: 100)
                }
            }
            .navigationDestination(for: Int.self) { value in
                Text("Selected box: \(value)")
            }
        }
        .onChange(of: path) { newPath in
            print("path: \(newPath)")
        }
    }
}

Thank you !

Output print statements
 
 
Q