如何将数组值放入按钮列表中,这些按钮将基于单击的内容打开新视图

问题描述 投票:1回答:2

如您所见,HStack非常冗余。我想要一个包含图像和文本的某种类型的数组但是我不知道如何将该数组放入列表中,更重要的是,我不知道如何识别单击了数组中的哪个元素并根据单击的内容打开了一个新视图。

struct ContentView: View {
    var body: some View {
        ZStack {
            NavigationView {
                List {

// as you can see the HStack is very redundant.
// I want to have an array of some type that contains both the image and the text
// But I do not know how to put that array into the list, more importantly I do not know how to recognize which element in the array was clicked and open a new view based on what is clicked
                    HStack {
                        Image("someImage")
                        .resizable()
                            .frame(width: 50, height: 50, alignment: .leading)
                        .clipShape(Circle())
                        NavigationLink (destination: SomeView()) {
                            Text("SomeText").foregroundColor(.gray)
                            .bold()
                        }
                    }
                    HStack {
                        Image("Image2")
                            .resizable()
                            .clipShape(Circle())
                            .frame(width: 50, height: 50, alignment: .leading)
                        NavigationLink(destination: image2()) {
                            Text("text2").foregroundColor(.gray)
                            .bold()
                        }
                    }
                    HStack {
                        Image("image3")
                            .resizable()
                            .clipShape(Circle())
                            .frame(width: 50, height: 50, alignment: .leading)
                        NavigationLink(destination: view3()) {
                            Text("view3").foregroundColor(.gray)
                            .bold()
                        }
                    }
                }.navigationBarTitle("list")
            }
        }
    }
}

如您所见,HStack非常冗余。我想有一个既包含图像又包含文本的某种类型的数组,但是我不知道如何将该数组放入列表中,更重要的是,我这样做了...

swift swiftui
2个回答
1
投票

您将需要3个不同的数组或模型,由于您的问题是关于数组的,因此我将使用第一种使用数组的方法进行演示。


1
投票

您可以这样做:

© www.soinside.com 2019 - 2024. All rights reserved.