我有一个类型为[Text]
的数组,我正试图使用ForEach
来渲染它,但它告诉我Text
需要符合Hashable
或Identifiable
。有什么不同的方法可以做到这一点吗?我确实尝试过Hashable实现:
extension Text: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(self)
}
}
但不幸的是,这并没有奏效。我不想添加Text
视图,因为我想控制它们之间的间距。
让我们说,从技术上讲,是可能的(老实说(
struct Demo1: View {
let texts = [Text("1"), Text("2"), Text("3"), Text("4")]
var body: some View {
VStack {
ForEach(texts.indices, id: .self) { texts[$0] }
}
}
}
然而,当然,通过SwiftUI,正确的是
struct Demo2: View {
let texts = ["1", "2", "3", "4"]
var body: some View {
VStack {
ForEach(texts.indices, id: .self) { Text(texts[$0]) }
}
}
}
由于SwiftUI是声明性的,我们只需要更改数据,让SwiftUI自己更新。因此,让你的ui依赖于数据本身,而不是另一个ui。
struct ContentView: View {
let yourTexts = ["1", "2", "3", "4"]
var body: some View {
VStack {
ForEach(yourTexts, id: .self) {
Text($0)
}
}
}
}