列表项中的按钮无法正常工作

时间:2020-01-16 16:31:27

标签: ios swift swiftui

我有2个视图:PollCard和PollList(如民意调查列表)
在PollCard视图中,我有2个按钮(图像),它们调用“ answer”功能:

HStack{
    Button(action: {
        self.answer()
        print("Pressed first image")
    }){
        Image(poll.v1img)
            .resizable()
            .renderingMode(.original)
            .scaledToFill()
            .frame(width: 150, height: 200)
    }.frame(width: 150, height: 200)
    Button(action: {  self.answer()}){
        Image(poll.v2img )
            .resizable()
            .renderingMode(.original)
            .frame(width: 150, height: 200)
    }.frame(width: 150, height: 200).zIndex(4)
}

PollList视图中,我有以下简单列表:

var body: some View {
    HStack{
        List(pollData) { poll in
            PollCard(poll: poll)
            }.padding()
    }
}

但是当我单击列表中的图像时,它会像所有图像一样选择并按下 Example
这也非常容易检查-即使我只按了第二张图像,终端也会打印Pressed first image


我该怎么做才能解决此问题?

1 个答案:

答案 0 :(得分:1)

正如我在评论部分中提到的,解决方法是将HStack周围的List替换为ScrollView,将List替换为ForEach


struct ContentView: View {

    struct Data: Identifiable {
        var id: Int
    }

    @State var data = [Data(id: 0), Data(id: 1), Data(id: 2), Data(id: 3), Data(id: 4), Data(id: 5)]

    var body: some View {
        ScrollView {
            ForEach(self.data) { data in
                HStack {
                    Button(action: {
                        print("Pressed blue...")
                    }, label: {
                        Rectangle()
                            .foregroundColor(Color.blue)
                            .frame(width: 150, height: 200)
                    })
                    Button(action: {
                        print("Pressed red...")
                    }, label: {
                        Rectangle()
                            .foregroundColor(Color.red)
                            .frame(width: 150, height: 200)
                    })
                }
            }
        }
    }
}

我希望这会有所帮助!