Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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))))
            
        }
    }
}
like image 244
Begbie Avatar asked Dec 16 '20 10:12

Begbie


2 Answers

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
}
like image 199
Asperi Avatar answered Oct 08 '22 23:10

Asperi


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")
        }
        
    }
}
like image 32
davidev Avatar answered Oct 08 '22 23:10

davidev