我有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()
}
}
但是当我单击列表中的图像时,它会像所有图像一样选择并按下
这也非常容易检查-即使我只按了第二张图像,终端也会打印Pressed first image
我该怎么做才能解决此问题?
答案 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)
})
}
}
}
}
}
我希望这会有所帮助!