Home > Mobile >  SwiftUI navigation works on iOS but fails on macOS
SwiftUI navigation works on iOS but fails on macOS

Time:06-21

I have an iOS SwiftUI app that works fine on iPhone and iPad, but when compiled for native macOS the navigation links are disabled. Code is below. Briefly, the FirstView is a NavigationView containing a List of NavigationLinks. These work, and link to a DetailView that contains a next level of NavigationLinks presented as Images.

On iOS, these images are active blue that when clicked, go to a FinalView.

On macOS, these images are inactive: Presented as gray, and don't have any click-ability.

Why do these appear differently on the two OS's? How to fix the macOS version so that it navigates? Thanks in advance

import SwiftUI

struct TNode {  // simple data struct that just carries name and ID
    public let id = UUID()
    public let name : String
    init( _ name:String) {
        self.name = name
    }
}

// starting view
struct FirstView: View {
    init () {
        // provide some sample data
        nodes = [TNode("node 1"), TNode("node 2")]
     }

    @State private var nodes : [TNode]

    var body: some View {
        NavigationView {
            List {
                ForEach(nodes, id:\.id) { (node) in
                    // where to go when selected
                    NavigationLink(destination:
                                    DetailView(displayNode: node)
                    ){ // display names for selection in the sidebar
                        VStack {
                            Text(node.name)
                        }
                    }
                }
            }
        }
    }
}

struct DetailView: View {
    let displayNode : TNode
    
    var body: some View {
        VStack(alignment: .leading) {
            
            Text(displayNode.name)
            
            HStack{
                // this is what doesn't work on macOS
                NavigationLink(destination: FinalView()) {
                    Image(systemName:"figure.stand.line.dotted.figure.stand")
                }
                 
                NavigationLink(destination: FinalView()) {
                        Image(systemName:"square.and.pencil")
                }
            }
        }
    }
}

struct FinalView : View {
    var body : some View {
        Text("Got to final view OK")
    }
}

Behavior on macOS:

macOS image with disabled links

Xcode 13.4.1, macOS Monterey 12.4

CodePudding user response:

Embed the VStack of the DetailView in a NavigationView. Remember that iOS is different than macOS.

In iOS you didn't need to wrap the child View of in a NavigationView because it's a child. With macOS this a standalone View.

CodePudding user response:

Remove Stack in Navigation link :

                ){ // display names for selection in the sidebar
// Remove VStack     VStack {
                        Text(node.name)
//                   }
                }
  • Related