SwiftUI-从数组中删除项目会导致致命错误:索引超出范围

时间:2020-05-21 10:18:16

标签: ios swift xcode swiftui

我是SwiftUI的新手,我正在尝试建立一个Image-Gallery,您可以在其中删除图像:

我的代码部分起作用,当有更多元素时,我不能删除的唯一元素是最后一个。

奇怪的事情:当我只有一个元素时,可以在一个视图中将其删除,而在另一个视图中,则会导致索引超出范围错误

这是我的代码

struct ImageSlider: View {
@Binding var images: [DefectImage]
@Binding var imagesTitels: [String]
@Binding var edit: Bool

var body: some View {
    ScrollView(.horizontal) {
        HStack {
            if self.images.count > 0 {
                ForEach(self.images) { img in
                    VStack {
                        if !self.edit {
                            DefImage(url: "", image: img.image)
                            Text(self.imagesTitels[self.getIdOfImg(img: img)])
                                .frame(width: 135)
                        }
                        else {
                            Button(action: {
                                self.imagesTitels.remove(at: self.getIdOfImg(img: img))
                                self.images.remove(at: self.getIdOfImg(img: img))
                            }){
                                DefEditImage(url: "", image: img.image)
                            }
                            .buttonStyle(PlainButtonStyle())

                            VStack {
                                TextField("", text: self.$imagesTitels[self.getIdOfImg(img: img)])
                                    .frame(width: 135)
                                    .offset(y: 6)
                                Rectangle()
                                    .frame(width: 135, height: 1.0, alignment: .bottom)
                                    .foregroundColor(Color.gray)
                            }
                        }
                    }
                }
            }
        }
    }
}



func getIdOfImg(img: DefectImage) -> Int {
    var countId: Int = 0
    for item in self.images {
        if img.id == item.id {
            return countId
        }

        countId += 1
    }

    return -1
}

错误:

Fatal error: Index out of range: file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-1103.2.25.8/swift/stdlib/public/core/ContiguousArrayBuffer.swift, line 444

该错误不在数组之一中: Screenshot of Error

1 个答案:

答案 0 :(得分:1)

为什么不尝试更改函数getIdOfImg。 不使用for循环,而是使用

func getIdOfImg(img: String) -> Int {
    if let index = self.images.firstIndex(of: img) {
        return index
    } else {
        return -1
    }
}

并重写该块

Button(action: {
    self.imagesTitels.remove(at: self.getIdOfImg(img: img))
    self.images.remove(at: self.getIdOfImg(img: img))
})

Button(action: {
    let index = self.getIdOfImg(img: img)
    if index > 0 && index < self.images.count {
        self.imagesTitels.remove(at: index)
        self.images.remove(at: index)
    }
})
相关问题