简体   繁体   中英

Passing the data from one view to another SwiftUI via NavigationLink

I am building an iOS application using SwiftUI. To be honest, I am a newbie to SwiftUI and Swift and Native IOS development. What I am trying to do now is that I am trying to pass data from one screen to another through NavigationLink. But the PreviewProvider of the destination provider is throwing an error.

I have the ContentView.swift with the following code

struct ContentView: View {
    var listItems = [ BleDevice ]()
    init() {
        listItems.append(BleDevice(id: "ID 1", name: "Name 1"))
        listItems.append(BleDevice(id: "ID 2", name: "Name 2"))
    }
    
    var body: some View {
        NavigationView {
            VStack() {
                List{
                    ForEach(listItems) {
                        item in VStack() {
                            Text(item.id)
                            Text(item.name)
                            NavigationLink(destination: ServicesListView(device: item)) {
                                Text("Connect")
                                    .padding()
                                    .foregroundColor(/*@START_MENU_TOKEN@*/.blue/*@END_MENU_TOKEN@*/)
                           Spacer()
                        }
                    }
                }.navigationTitle("Devices")
                }
            }
        }
        .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

As you can see I am trying to pass device object to the destination view. This is my ServicesListView.swift

import SwiftUI

struct ServicesListView: View {
    var device: BleDevice
    
    var body: some View {
        Text(/*@START_MENU_TOKEN@*/"Hello, World!"/*@END_MENU_TOKEN@*/)
    }
}

struct ServicesListView_Previews: PreviewProvider {
    static var previews: some View {
        ServicesListView()
    }
}

But when I tried to compile the project, ServicesListView_Previews class is complaining, "Missing argument for parameter 'device' in call" as follow. I know that it is because it is not initialising the ServicesListView class with the parameter. But how can I pass the data to it too?

For preview just pass static data like this

struct ServicesListView_Previews: PreviewProvider {
    static var previews: some View {
        ServicesListView(device: BleDevice(id: "ID 1", name: "Name 1"))
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM