【问题标题】:SwiftUI unexpected index with ForEach Loop and Picker带有 ForEach 循环和选取器的 SwiftUI 意外索引
【发布时间】:2020-08-08 17:52:58
【问题描述】:

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

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

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

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")
            }
        }
        
    }
}

【问题讨论】:

    标签: ios swift xcode swiftui


    【解决方案1】:

    您的代码一切正常,您只是在透明空间中点击,默认情况下不处理。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-14
      相关资源
      最近更新 更多