简体   繁体   English

ForEach onDelete Mac

[英]ForEach onDelete Mac

I am trying to figure out how to delete from an array in swiftui for Mac.我想弄清楚如何从 swiftui for Mac 中的数组中删除。 All the articles that I can find show how to do it the UIKit way with the .ondelete method added to the foreach.我能找到的所有文章都展示了如何使用 UIKit 方法将 .ondelete 方法添加到 foreach。 This is does not work for the Mac because I do not have the red delete button like iOS does.这不适用于 Mac,因为我没有像 iOS 那样的红色删除按钮。 So how do I delete items from an array in ForEach on Mac.那么如何在 Mac 上的 ForEach 中从数组中删除项目。 here is the code that I have tried, which gives me the error这是我尝试过的代码,它给了我错误

Fatal error: Index out of range: file

import SwiftUI

struct ContentView: View {

    @State var splitItems:[SplitItem] = [
        SplitItem(id: 0, name: "Item#1"),
        SplitItem(id: 1, name: "Item#2")
    ]

    var body: some View {
        VStack {
            Text("Value: \(self.splitItems[0].name)")
            ForEach(self.splitItems.indices, id:\.self) { index in
                HStack {
                    TextField("Item# ", text: self.$splitItems[index].name)
                    Button(action: {self.removeItem(index: index)}) {Text("-")}
                }
            }
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
    }

    func removeItem(index:Int) {
        self.splitItems.remove(at: index)
    }

}

struct SplitItem:Identifiable {
    var id:Int
    var name:String
}

Your ForEach code part is completely correct.您的ForEach代码部分是完全正确的。 The possible error source could be the line Text("Value: \\(self.splitItems[0].name)") - after deleting all items this will definitely crash.可能的错误来源可能是行Text("Value: \\(self.splitItems[0].name)") - 删除所有项目后,这肯定会崩溃。

The next assumption is the VStack .下一个假设是VStack After Drawing a view hierarchy it will not allow to change it.绘制视图层次结构后,将不允许更改它。 If you replace the VStack with Group and the next code will work:如果您用Group替换 VStack 并且下一个代码将起作用:

var body: some View {
    Group {
        if !self.splitItems.isEmpty {
            Text("Value: \(self.splitItems[0].name)")
        } else {
            Text("List is empty")
        }
        ForEach(self.splitItems.indices, id:\.self) { index in
            HStack {
                TextField("Item# ", text: self.$splitItems[index].name)
                Button(action: {self.removeItem(index: index)}) {Text("-")}
            }
        }
    }
    .frame(maxWidth: .infinity, maxHeight: .infinity)
}

so I was able to find the answer in this article ,所以我能够在这篇文章中找到答案,

instead of calling array.remove(at) by passing the index from the for loop call it using array.FirstIndex(where).而不是通过传递来自 for 循环的索引来调用 array.remove(at) 使用 array.FirstIndex(where) 调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM