如何获取列表SwiftUI中某行的IndexSet的整数值

xfyts7mz  于 2022-12-17  发布在  Swift
关注(0)|答案(2)|浏览(161)

我有一个包含五种不同类型的水果名称的数组,我有一个显示这个数组的列表,当我删除一个水果时,我想得到一个整数,它反映了这个水果在列表中的位置(现在我并不关心从列表中删除水果)。例如,banana应该在第1行,apple应该在第2行,有没有办法用IndexSet的某个函数来获得这个整数?
下面是代码:

var fruits:[String] = ["banana", "apple", "grape", "pear", "kiwi"]

List {
            ForEach(fruits) {fruit in
                Text(fruit)
            }
            .onDelete(perform: obtainingTheRowNumber)
}

func obtainingTheRowNumber(indexSet: IndexSet) -> Int {
//I want this function to return the row number of the object being deleted but I'm not sure how. 
}

我试着查看有关IndexSet的文档,但我什么也找不到,我觉得我错过了一些超级简单的东西。

ycl3bljg

ycl3bljg1#

您可以使用下面的代码...

func obtainingTheRowNumber(indexSet: IndexSet){
        let index = indexSet[indexSet.startIndex] // get index from here
        print(index) 
    }
snz8szmq

snz8szmq2#

struct ContentView: View {
   
    var fruits:[String] = ["banana", "apple", "grape", "pear", "kiwi"]

    var body: some View {
        List {
            ForEach(fruits, id:\.self) {fruit in
                        Text(fruit)
                    
                    }
                    .onDelete(perform: obtainingTheRowNumber)
        }

        
        
   
    }
    
    func obtainingTheRowNumber(indexSet: IndexSet)   {
        for index in indexSet {
            print(index + 1)
        }
    }
        
}

相关问题