Begbie
Begbie

Reputation: 303

NavigationLink View Parameter SwiftUI

When I call NavigationImageView in my View , I want to send different View in every call , so I can navigate different views.But the problem is how can I send View parameter in NavigationLink. I tried View and UIView but it gives me error.

struct NavigationImageView: View {
    
    var item : Store
    var destinationView: View
    
    var body: some View {
        
        NavigationLink(destination:destinationView ) {
            
            Image(uiImage: (item.banner?.url)!.load())
                .resizable()
                .aspectRatio(CGFloat((item.banner?.ratio)!), contentMode: .fit)
                .cornerRadius(12)
                .shadow(radius: 4)
                .frame(width: CGFloat(UIScreen.main.bounds.width * 0.9), height: CGFloat((UIScreen.main.bounds.width / CGFloat((item.banner?.ratio) ?? 1))))
            
        }
    }
}

Upvotes: 6

Views: 2272

Answers (2)

Asperi
Asperi

Reputation: 257493

You need to use generics here, because type of destination view is not known in advance:

struct NavigationImageView<DestinationType: View>: View {
    
    var item : Store
    var destinationView: DestinationType

    // ... other code
}

Upvotes: 6

davidev
davidev

Reputation: 8517

Take a look at the following example...

Your property has to be any View and then you can assign any View to it which you will use as your destination.

import SwiftUI

struct ContentView: View {
    
    @State var showViewTwo : Bool = false
    
    //computed property of type some View which returns different views depending on a condition
    var destination : some View { 
        if showViewTwo {
            return Text("Hello Second View")
        }
        else
        {
            return Text("Hello First View")
        }
    }
    
    var body: some View {
        
        NavigationView {
           NavigationLink("Press me", destination: destination)
        }
        
        Button(action: {
            showViewTwo.toggle()
        }) {
            Text("Toggle View")
        }
        
    }
}

Upvotes: 2

Related Questions