gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 06:10:50 25 4
gpt4 key购买 nike

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

像这样

但我在 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])")
}
}

最佳答案

使用 .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)
}
}

关于swift - 如何在 SwiftUI 列表中获取行索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57842214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com