我对Swift
比较陌生。我想实现weatherList
的第一个项目以不同的视图显示。
不幸的是,我在这两行(VStack and at ForEach-Line)
中得到了这个错误。如果我把if i == 0
放在那里,只用于所有listitems
的正常布局,那么没有错误。
ERROR: Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols
这是我的代码:
var body: some View {
NavigationView {
VStack { // here first error
if self.model.error != nil {
Text(self.model.error!)
}
ForEach(0..<self.model.weatherList.count, id: .self) { i in // here second error
if i == 0 {
NavigationLink(destination: DetailView(model: self.model.weatherList[i])) {
RowView(model: self.model.weatherList[i])
}
}
else{
NavigationLink(destination: DetailView(model: self.model.weatherList[i])) {
RowView(model: self.model.weatherList[i])
}
}
}
}
.navigationBarTitle(Text("Weather in " + UserSettings.instance.locationSetting))
.navigationBarItems(trailing:
Button(action: {
self.model.reload()
}) {
Image(systemName: "arrow.clockwise")
}
.disabled(model.reloading)
)
}
}
非常感谢每一个建议。谢谢
我还没有尝试过,但如果你像这样包装NavigationLink呢:
if i == 0 {
AnyView(
NavigationLink(destination: DetailView(model: self.model.weatherList[i])) {
RowView(model: self.model.weatherList[i])
})
} else {
AnyView(
NavigationLink(destination: DetailView(model: self.model.weatherList[i])) {
RowView(model: self.model.weatherList[i])
})
}
如果没有剩下的代码来编译,要确定这一点有点棘手,但我在本地对它进行了模拟,看起来你只需要更改:
ForEach(0..<self.model.weatherList.count, id: .self) { i in
至
ForEach(0..<self.model.weatherList.count) { i in // remove the id: argument
说明:
如果您使用范围来遍历数组,则不使用id:参数。该范围可自动识别。ForEach(_:id:content:)
初始化程序用于您可能会说的情况
ForEach(self.model.weatherlist, id: .self) { model in
SomeView(model: model)
}
这是为你编译的吗?
编辑:无论索引是否为0,您给出的示例看起来都会做同样的事情。如果你尝试,它不起作用有原因吗:
ForEach(0..<self.model.weatherList.count) { i in
NavigationLink(destination: DetailView(model: self.model.weatherList[i])) {
RowView(model: self.model.weatherList[i])
}
}