我有一个带有两个属性的简单对象模型,第二个属性实际上是一个字符串数组。在一个简单的视图中,我想显示第一个属性,即roleName,并在其下方遍历第二个属性,以将它们显示在列表中或使用forEach循环。我用一个独立的String数组测试了它的工作原理,但是这种方式不会显示动作。谢谢您的帮助。下面的代码:
import SwiftUI
struct ActionsView: View {
var role = Role(roleName: "Witch", roleActions: ["Action 1","Action 2"])
var body: some View {
VStack(spacing: 20) {
Text(role.roleName)
.font(.title).fontWeight(.heavy)
VStack() {
Text("Choose Your Actions")
.font(.headline)
List(role.roleActions, id: \.self) { action in
HStack {
Text(action)
}
}
}
}
}
}
struct ActionsView_Previews: PreviewProvider {
static var previews: some View {
ActionsView()
}
}
答案 0 :(得分:0)
你的意思是这样吗?
import SwiftUI
struct Role : Identifiable, Hashable {
var id = UUID().uuidString
var roleName: String
var roleActions: [String]
}
struct RowView : View {
var role : Role
var body: some View {
ScrollView(.horizontal, content: {
HStack {
ForEach(role.roleActions, id: \.self) { action in
Text(action)
}
}
})
}
}
struct ContentView: View {
var roles = [Role(roleName: "Witch", roleActions: ["Action 1","Action 2"]),
Role(roleName: "Hero", roleActions: ["Action 3", "Action4"])]
var body: some View {
List (roles, id: \.self) { role in
Text(role.roleName)
.font(.title).fontWeight(.heavy)
VStack() {
Text("Choose Your Actions")
.font(.headline)
RowView(role: role)
}
}.environment(\.defaultMinListRowHeight, 140)
}
}