如何在 SwiftUI 列表中获取行索引? [英] How to get row index in SwiftUI List?

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

问题描述

我想要一个编号列表,其中每一行都有一个数字.

I would like to have a numbered list, where every row has a number.

像这样

但我在 List 初始化程序

but I don't see right API for that in List initialisers

此时我看到了这个解决方法

At this moment I see this workaround

var persons = ["Boris", "Anna", "Tom"]

// MARK: - Body
func body(props: Props) -> some View {
    List(persons.indices, id: \.self) { index in
        Text("\(index) \(self.persons[index])")
    }
}

推荐答案

使用 .indices() 不是一种解决方法,而是一种正确的方法.

Using .indices() is not a workaround, it is a proper way of doing it.

或者,您也可以将发行说明中的​​代码用于 indexed() 数组:

Alternatively, you can also use the code in the release notes for an indexed() array:

struct ContentView: View {
    var persons = ["Boris", "Anna", "Tom"]

    var body: some View {
        VStack {
            List(persons.indexed(), id: \.1.self) { idx, person in
                Text("\(idx) - \(person)")
            }
        }
    }
}


// This is taken from the Release Notes, with a typo correction, marked below
struct IndexedCollection<Base: RandomAccessCollection>: RandomAccessCollection {
    typealias Index = Base.Index
    typealias Element = (index: Index, element: Base.Element)

    let base: Base

    var startIndex: Index { base.startIndex }

   // corrected typo: base.endIndex, instead of base.startIndex
    var endIndex: Index { base.endIndex }

    func index(after i: Index) -> Index {
        base.index(after: i)
    }

    func index(before i: Index) -> Index {
        base.index(before: i)
    }

    func index(_ i: Index, offsetBy distance: Int) -> Index {
        base.index(i, offsetBy: distance)
    }

    subscript(position: Index) -> Element {
        (index: position, element: base[position])
    }
}

extension RandomAccessCollection {
    func indexed() -> IndexedCollection<Self> {
        IndexedCollection(base: self)
    }
}

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

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