在 SwiftUI 中获取 ForEach 中的索引 [英] Get index in ForEach in SwiftUI

查看:40
本文介绍了在 SwiftUI 中获取 ForEach 中的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,我想遍历它,根据数组值初始化视图,并希望根据数组项索引执行操作

I have an array and I want to iterate through it initialize views based on array value, and want to perform action based on array item index

当我遍历对象时

ForEach(array, id: \.self) { item in
  CustomView(item: item)
    .tapAction {
      self.doSomething(index) // Can't get index, so this won't work
    }
}

所以,我尝试了另一种方法

So, I've tried another approach

ForEach((0..<array.count)) { index in
  CustomView(item: array[index])
    .tapAction {
      self.doSomething(index)
    }
}

但是第二种方法的问题是,例如,当我更改数组时,如果 doSomething 执行以下操作

But the issue with second approach is, that when I change array, for example, if doSomething does following

self.array = [1,2,3]

ForEach 中的视图不会改变,即使值改变了.我相信,这是因为 array.count 没有改变.

views in ForEach do not change, even if values are changed. I believe, that happens because array.count haven't changed.

有没有办法解决这个问题?提前致谢.

Is there a solution for this? Thanks in advance.

推荐答案

这对我有用:

struct ContentView: View {
    @State private var array = [1, 1, 2]

    func doSomething(index: Int) {
        self.array = [1, 2, 3]
    }
    
    var body: some View {
        ForEach(0..<array.count) { i in
          Text("\(self.array[i])")
            .onTapGesture { self.doSomething(index: i) }
        }
    }
}

使用数组的索引

indices 属性是一个数字范围.

Using Array's Indices

The indices property is a range of numbers.

struct ContentView: View {
    @State private var array = [1, 1, 2]

    func doSomething(index: Int) {
        self.array = [1, 2, 3]
    }
    
    var body: some View {
        ForEach(array.indices) { i in
          Text("\(self.array[i])")
            .onTapGesture { self.doSomething(index: i) }
        }
    }
}

这篇关于在 SwiftUI 中获取 ForEach 中的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆