![](/img/trans.png)
[英]Looping two arrays of different type items (string and image) with ForEach SwiftUI
[英]Looping multiple arrays with ForEach SwiftUI
用户界面: https://imgur.com/a/0BbJBFc
我正在使用ForEach
在示例代码中迭代一系列矿物质,但我找不到合适的解决方案来循环矿物质下方的第二个数组(矿物质量)。
在不同的项目中,到目前为止,我做到了ForEach
循环 arrays 但每种矿物都显示Planet
的所有数量,第二种矿物显示Planet
的所有数量,依此类推。
我确实用 arrays 创建了一个新结构,但没有成功。 添加绑定属性也失败了。 我希望学习一个新的swift方法来实现愿望的样子。
数据文件
import Foundation
struct Planet: Identifiable {
var id = UUID()
var name: String
var minerals: [String]
var mineralAmount: [String]
}
let planetsData: [Planet] = [
Planet(name: "Jupiter", minerals: ["Iron", "Gold", "Copper"], mineralAmount: ["10K", "20K", "30K"]),
Planet(name: "Earth", minerals: ["Lithium", "Aluminium", "Quartz"], mineralAmount: ["40K", "50K", "60K"])
]
内容视图
import SwiftUI
struct ContentView: View {
var planet: Planet
var body: some View {
VStack() {
ForEach(planet.minerals, id: \.self) { item in
Text(item)
.font(.system(size: 22, weight: .regular))
.foregroundColor(.primary)
Text("amount to be added")
.font(.system(size: 22, weight: .regular))
.foregroundColor(.primary)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(planet: planetsData[0])
}
}
[1]: https://i.stack.imgur.com/4MDKs.png
你为什么不从这两个值创建一个字典
mineralsDic = [minerals: mineralAmount]
我当然知道dictionary
的语法,但我只是试图解释我的想法 + 而不是制作 2 个循环,你可以只制作一个复杂性更低且性能更好的循环
您可以通过以下方式实现:
ScrollView {
VStack (alignment: .leading) {
ForEach(0..<planet.minerals.count) { i in
HStack {
Circle()
.frame(width: 50, height: 50)
.foregroundColor(.black)
VStack (alignment: .leading) {
Text(planet.minerals[i])
.font(.system(size: 22, weight: .regular))
.foregroundColor(.primary)
Text(planet.mineralAmount[i])
.font(.system(size: 22, weight: .regular))
.foregroundColor(.secondary)
}
}
}
Spacer()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.