Home > Net >  How do I put Arrays inside Arrays into ForEach in SwiftUI?
How do I put Arrays inside Arrays into ForEach in SwiftUI?

Time:06-23

I have following Code, however, I cant get the respective element to be shown.

struct MyUserView: View {

let Users = [
["name": "Manuelle", "age": 23, "profilePicture": Image(systemName: "person"), "status": "inactive", "icon": Image(systemName: "message.fill")],
    
["name": "Michael", "age": 39, "profilePicture": Image(systemName: "person"), "status": "active 12 minutes ago", "icon": Image(systemName: "square.on.square")]
]

var body: some View {
    NavigationView {
        List {
ForEach(Users.indices, id:\.self) { user in
HStack {
Text(Data[user]["name"]!)
Image(UIImage(Data[user]["profilePicture"]!))
}
}
}

CodePudding user response:

There are many, many issues.

First create a struct User for the model, the members profilePicture and icon are declared as String rather than as a SwiftUI view.

struct User : Hashable {
    let name: String
    let age: Int
    let profilePicture, status, icon: String
}

In the view use the struct which is more comfortable for several reasons

struct MyUserView: View {
    
    let users = [
        User(name: "Manuelle", age: 23, profilePicture: "person", status: "inactive", icon: "message.fill"),
        User(name: "Michael", age: 39, profilePicture: "person", status: "active 12 minutes ago", icon: "square.on.square")
    ]
    
    var body: some View {
        NavigationView {
            List {
                ForEach(users, id: \.self) { user in
                    HStack {
                        Text(user.name)
                        Image(systemName: user.profilePicture)
                    }
                }
            }
        }
    }
}
  • Related