如何在SwiftUI列表中获取行索引?

Tik*_*der 2 swift swiftui swiftui-list

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

像这样

但是我在List初始化器中看不到正确的API

目前,我看到了这种解决方法

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])")
    }
}
Run Code Online (Sandbox Code Playgroud)

onm*_*133 7

您可以使用enumerated,例如https://github.com/onmyway133/blog/issues/515

struct CountriesView: View {
    let countries: [Country]

    var body: some View {
        let withIndex = countries.enumerated().map({ $0 })

        return List(withIndex, id: \.element.name) { index, country in
            NavigationLink(
                destination: CountryView(country: country),
                label: {
                    VStack(alignment: .leading) {
                        Text(country.name)
                            .styleMultiline()
                    }
                    .paddingVertically()
                }
            )
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果我想传递一个 Binding 数组怎么办? (2认同)

kon*_*iki 6

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

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

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @kontiki,是的,它有效,但是当我在 List/ForEach 中添加 if 条件时,出现错误“类型 '_' 没有成员 '1'”。 (2认同)