如何解决SwiftUI:使用 ForEach 动态加载图像
我想使用数据来驱动显示的图像。这是 places
可以是什么的示例:
let places = {
names: ["area","volume"]
}
我在下面尝试了类似的方法,但得到了 Referencing initializer 'init(_:content:)' on 'ForEach' requires that 'String' conform to 'Identifiable'
ForEach(places.name) { place in
NavigationLink (destination: Any()) {
HStack {
Image(place)
}
解决方法
对于像 String
这样不直接符合 Identifiable
的类型,您可以告诉 ForEach
使用什么属性作为 id
。通常对于 String
,您会想要使用 .self
(请注意,如果 String
不是唯一的,这会产生有趣的结果)。
struct Places {
var names : [String]
}
struct ContentView : View {
let places : Places = Places(names: ["area","volume"])
var body: some View {
ForEach(places.names,id:\.self) { place in
NavigationLink (destination: Text("Detail")) {
HStack {
Image(place)
}
}
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。