代码之家  ›  专栏  ›  技术社区  ›  Mahendra

Popover不是从SwiftUI中的项目列表中打开的[重复]

  •  1
  • Mahendra  · 技术社区  · 4 月前

    我有一个项目列表,当用户点击它时,我需要在中显示一些内容 .popover() .

    型号:

    struct Item: Identifiable {
      var id: String {
         UUID().uuidString
      }
      var name: String?
      var addr: String?
    
      init(name: String? = nil, addr: String? = nil) {
        self.name = name
        self.addr = addr
      }
    }
    

    查看:

    struct ContentView: View {
      let arr = [
        Item(name: "Roman", addr: "Address of Roman"),
        Item(name: "Alexa", addr: "Address of Alexa"),
      ]
      @State private var selection: Item?
    
      var body: some View {
        VStack {
            List {
                ForEach(arr) { item in
                    Text(item.name!)
                        .id(item.name!)
                        .onTapGesture {
                            selection = item
                            print("selection: \(item.name ?? "")")
                        }
                        .popover(item: $selection) { item in
                            Text(item.addr ?? "")
                        }
                    
                }
            }
         }
      }
    

    当用户点击 name 流行歌曲没有出现。

    如果列表中只有一个项目,则弹出窗口将按预期显示(如下图所示)。

    enter image description here

    为什么popover在项目列表中没有按预期工作?

    这是SwiftUI中的错误吗?

    2 回复  |  直到 4 月前
        1
  •  1
  •   Mojtaba Hosseini    4 月前

    问题是因为您正在分配 single binding to multiple popovers 。您应该区分每行的绑定,例如为每行创建不同的绑定:

    ForEach(arr) { item in
        let binding = Binding<Item?>(
            get: { selection == item ? item : nil }, // 👈 returns the item only for the corresponding row
            set: { selection = $0 }
        )
        
        Text(item.name!)
            .id(item.name!)
            .onTapGesture {
                selection = item
                print("selection: \(item.name ?? "")")
            }
            .popover(item: binding) { item in // 👈 Use the specified binding here
                Text(item.addr ?? "")
            }
    }
    

    别忘了做 Item: Equatable .