首页 > 解决方案 > SwiftUI - removeAll 的错误索引(其中:)

问题描述

我想让用户删除数组中的图像。按下图像时,会显示一个操作表,以便用户确认删除图像。问题是它删除了错误的图像。它总是删除数组的第一个图像。

@State var pickerResult: [SImage] = []

...

ScrollView(.horizontal, showsIndicators: true){
  HStack{
    ForEach(pickerResult) { simage in
      Image(uiImage: simage.image)
        .onTapGesture() {
          imageActionSheetIsPresented = true
          // This will work: self.pickerResult.removeAll(where: {$0.image == simage.image})
        }
        .actionSheet(isPresented: $imageActionSheetIsPresented) {
          ActionSheet(title: Text("Do you want to remove the image?"), buttons: [
            .default(Text("Remove image")){
              self.pickerResult.removeAll(where: {$0.image == simage.image})
              print(simage.id)
              // Returns id of the first image in the array
            },
            .cancel()
          ])
        }
    }
  }
}

正如您在代码中看到的,跳过确认并让用户使用 onTap 删除图像就可以了。使用 ActionSheet 时,“图像”始终是数组中的第一项。

这是SImage:

struct SImage: Identifiable{
    var id = UUID()
    var image: UIImage
}

标签: swiftui

解决方案


推荐阅读