当 List 被数组填充时,如何在 SwiftUI 中获取 List 中元素的索引? [英] How to get the index of the element in the List in SwiftUI when the List is populated with the array?

查看:52
本文介绍了当 List 被数组填充时,如何在 SwiftUI 中获取 List 中元素的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 SwiftUI 应用中,我有一个项目列表.

In my SwiftUI app, I have a list of items.

我正在使用 MenuItem 的数组来填充列表

I'm using the array of MenuItems to fill in the list

struct MenuItem: Identifiable, Equatable {
                    var id = UUID()
                    var text: String
}

struct MenuView: View {

var menuItems = [MenuItem(text:"Text1"),MenuItem(text:"Text2")]

                 var body: some View {

                  List {

                                ForEach(menuItems) {textItem in

                   Text(textItem.text)

             }

        }

        }

    }

问题是,如何获取textItem的索引?

The question is, how to get the index of textItem?

例如,如果我想为奇数行和偶数行设置不同的行颜色,或者我是否需要为编号为 3 的行实现不同的样式?

For example if I want to have different row colors for odd and even rows, or if I need to implement different styling for the row with number 3?

在 SwiftUI 中获取 List 中项目索引的最佳方法是什么?

What is the best way to get the index of the item in the List in SwiftUI?

推荐答案

这可以使用 .enumerated 来完成.对于您的 MenuItem 值,它将如下所示

This can be done using using .enumerated. For your MenuItem values it will be as follows

List {
    ForEach(Array(menuItems.enumerated()), id: \.1.id) { (index, textItem) in
        // do with `index` anything needed here
        Text(textItem.text)
    }
}

这篇关于当 List 被数组填充时,如何在 SwiftUI 中获取 List 中元素的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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