[英]SwiftUI Picker population problem - ForEach Loop in picker does not populate
[英]SwiftUI unexpected index with ForEach Loop and Picker
我想構建一個自定義列表,允許用戶 select 一個條目導致選擇器顯示。
由於 Picker 比默認條目占用更多空間,因此 List 中的其他元素應相應移動。 我使用了 ForEach 循環和 VStack 來實現該目標。
但是,有時 onTapGesture 不會做任何事情。 調試我的代碼,我發現 onTapGesture 的工作方式與它應該的一樣——但是被點擊條目的索引是錯誤的。 請參見下面的 GIF:單擊“1”和“2”應導致索引為“1”和“2”的 output,但事實並非如此。 有人知道為什么嗎? 非常感謝!
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")
}
}
}
}
您的代碼一切正常,您只是在透明空間中點擊,默認情況下不處理。
這是修復 - 剛剛使整個區域可用(使用 Xcode 12 / iOS 14 測試)
.contentShape(Rectangle()) // << fix !!
.onTapGesture {
withAnimation(.spring()){
// print(elem) // << here if you want
self.selectedElement = elem
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.