我正在尝试使用数据数组的ForEach和NavigationLink创建一个列表。
我相信我的代码(见文章末尾(是正确的,但由于"调用"中缺少参数"index"的参数;带我去SceneDelegate.swift,这是我以前从未去过的地方。
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
如果我修改为,我可以运行代码;
let contentView = ContentView(habits: HabitsList(), index: 1)
但是我的所有链接都持有相同的数据,这是有意义的,因为我正在命名索引位置。
我尝试过,index:self.index(这是我在NavigationLink中使用的(,但得到了不同的错误消息-无法转换类型为"(Any("的值->Int"转换为预期的参数类型"Int">
以下是我的代码片段供参考;
struct HabitItem: Identifiable, Codable {
let id = UUID()
let name: String
let description: String
let amount: Int
}
class HabitsList: ObservableObject {
@Published var items = [HabitItem]()
}
struct ContentView: View {
@ObservedObject var habits = HabitsList()
@State private var showingAddHabit = false
var index: Int
var body: some View {
NavigationView {
List {
ForEach(habits.items) { item in
NavigationLink(destination: HabitDetail(habits: self.habits, index: self.index)) {
HStack {
VStack(alignment: .leading) {
Text(item.name)
.font(.headline)
Text(item.description)
}
}
}
}
}
}
}
}
struct HabitDetail: View {
@Environment(.presentationMode) var presentationMode
@ObservedObject var habits: HabitsList
var index: Int
var body: some View {
NavigationView {
Form {
Text(self.habits.items[index].name)
}
}
}
}
您可能不需要将整个ObservedObject
传递给HabitDetail
。
只通过一个HabitItem
就足够了:
struct HabitDetail: View {
@Environment(.presentationMode) var presentationMode
let item: HabitItem
var body: some View {
// remove `NavigationView` form the detail view
Form {
Text(item.name)
}
}
}
然后您可以修改您的ContentView
:
struct ContentView: View {
@ObservedObject var habits = HabitsList()
@State private var showingAddHabit = false
var body: some View {
NavigationView {
List {
// for every item in habits create a `linkView`
ForEach(habits.items, id:.id) { item in
self.linkView(item: item)
}
}
}
}
// extract to another function for clarity
func linkView(item: HabitItem) -> some View {
// pass just a `HabitItem` to the `HabitDetail`
NavigationLink(destination: HabitDetail(item: item)) {
HStack {
VStack(alignment: .leading) {
Text(item.name)
.font(.headline)
Text(item.description)
}
}
}
}
}