gra*_*ell 39
这是一个简单的修复。将数组传递给 时List,数组中的元素需要符合Identifiable协议。String不符合Identifiable,所以使这项工作的方法是这样使用.identified(by:):
struct StringList: View {
let strings = ["1234", "5678"]
var body: some View {
List(strings.identified(by: \.self)) { string in
Text(string)
}
}
}
Run Code Online (Sandbox Code Playgroud)
您还可以使用ForEach内部List:
struct StringList: View {
let strings = ["1234", "5678"]
var body: some View {
List {
ForEach(strings.identified(by: \.self)) { string in
Text(string)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这两个示例都实现了相同的输出,但第一个示例更简洁,需要的代码更少。
作为测试版的Xcode 4的,identified(by:)已被弃用,取而代之的特定初始化的List和ForEach:
struct StringList: View {
let strings = ["1234", "5678"]
var body: some View {
List(strings, id: \.self) { string in
Text(string)
}
}
}
Run Code Online (Sandbox Code Playgroud)
struct StringList: View {
let strings = ["1234", "5678"]
var body: some View {
List {
ForEach(strings, id: \.self) { string in
Text(string)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7220 次 |
| 最近记录: |