使用ForEach循环和Picker的SwiftUI意外索引

时间:2020-08-08 17:52:58

标签: ios swift xcode swiftui

我想构建一个自定义列表,该列表允许用户选择一个导致选择器显示的条目。

由于Picker比默认条目占用更多的空间,因此List中的其他元素也应相应移动。我使用了ForEach循环和VStack来实现该目标。

但是,有时onTapGesture不执行任何操作。调试我的代码后,我发现onTapGesture的工作原理与它应有的一样-但被窃听的条目的索引错误。请参阅下面的GIF:单击“ 1”和“ 2”应导致输出索引“ 1”和“ 2”,但事实并非如此。有人知道为什么吗?非常感谢!

enter image description here

struct ContentView: View {
    @State var timeList: [Int] = [1, 2, 3]
    @State var selectedElement = 0
    @State var sec = 0
    
    var body: some View {
        ScrollView(){
            VStack{
                ForEach(timeList, id: \.self){ elem in
                    ZStack{
                        VStack{
                            
                            ZStack{
                                Rectangle()
                                    .cornerRadius(elem == self.selectedElement ? 20 : 50)
                                    .frame(height: elem == self.selectedElement ? 120 : 40)
                                    .foregroundColor(Color.gray.opacity(0.3))
                                    .padding()
                                
                                Text("\(elem)").opacity(elem == self.selectedElement ? 0 : 1)
                            }
                        }
                        
                        if(elem == self.selectedElement){
                            HStack{
                                Spacer()
                                
                                Picker(selection: self.$sec, label: Text("")){
                                    Text("abc")
                                }
                                
                                Spacer()
                            }
                        }
                    }
                    .frame(height: elem == self.selectedElement ? 100 : 30)
                    .padding()
                    .onTapGesture {
                        withAnimation(.spring()){
                            self.selectedElement = elem
                            print(self.selectedElement)
                        }
                    }
                }
            }
            Spacer()
            
            Button(action: {
                self.timeList.append(5)
            })
            {
                Text("add")
            }
        }
        
    }
}

1 个答案:

答案 0 :(得分:1)

您的代码一切都很好,您只需在透明的空间中轻按即可,默认情况下不会对其进行处理。

这里已修复-刚刚使整个区域都可用(已通过Xcode 12 / iOS 14测试)

.contentShape(Rectangle())    // << fix !!
.onTapGesture {
    withAnimation(.spring()){
//        print(elem)     // << here if you want
        self.selectedElement = elem
    }
}