我无法将数据传输到每个索引

I can't transfer data to each index

我正在尝试从第一个视图传输相同的 API 数据并在第二个视图中显示其余详细信息

问题是在所有索引中显示相同的第一个数据

struct model: Codable, Identifiable {

let id = UUID()
var details : String
var title : String
}

并在此处获取数据

class Api : ObservableObject{

@Published var models : [model] = []

func getData (url : String) {
    
    guard let url = URL(string: url) else { return }
    var request = URLRequest(url: url)
    
    request.setValue("Bearer \(APIgetURL.Token)", forHTTPHeaderField: "Authorization")
    
    URLSession.shared.dataTask(with: request) { data, responce, err in
        
        guard let data = data else { return }
        
        do {
            let dataModel = try JSONDecoder().decode([model].self, from: data)

            DispatchQueue.main.async {
                self.models = dataModel
            }

        } catch {
            print("error: ", error)
        }
    }
    .resume()
}
}

这里我以第一个视图展示数据

ForEach(modelname.models) { item in
        
        NavigationLink(destination: DetilesTap1(modelname: modelname)) {
            
            Rectangle()
                .cornerRadius(15)
                .frame(width: .infinity, height: 40)
                .foregroundColor(.white)
                .shadow(color: .black.opacity(0.3), radius: 20)
                .padding(.trailing).padding(.leading)
            
                .overlay(
                    HStack {
                        Text(item.title)
                            .padding(.trailing,30).padding(.leading,30)
                        Spacer()
                        Image(systemName: "arrow.down.doc.fill")
                            .padding(.trailing,30).padding(.leading,30)
                    }
                )
        }
    }

这是第二个视图

ForEach(modelname.models) { item in
            VStack(alignment: .center) {
                VStack(spacing: 10) {
                    Text(item.title)
                    Text(item.details)
                    Spacer()
                }
            }
        }

我试过把id和同样的问题

尽管所有解释和方法可用,但它们都有相同的问题

您还没有发布 Minimal Reproducible Example (MRE),所以这是一个有根据的猜测。假设

@StateObject var modelname = Api()

那么您的第一个视图应该是:

// keep you naming consistent. item is really of type Model, so call it model.
ForEach(modelname.models) { model in
        // Pass just the model data you want to display, not everything.
        NavigationLink(destination: DetilesTap1(model: model)) {
...
}

在你的第二个视图中:

struct DetailView: View {

    let model: Model

    var body: some View {
        // the two VStack were redundant.
         VStack(alignment: .center, spacing: 10) {
              Text(model.title)
              Text(model.details)
              Spacer()
        }
    }
}

你只需要传递你想要显示的数据,而不是一切都重新来过。那就是ForEach的重点了。它允许您获取每个元素并单独处理它,而无需索引。请学习Apple’s SwiftUI Tutorials & Stanford’s CS193P。您需要更好地了解 SwiftUI 的工作原理。