SwiftUI 中 ForEach 和 NavigationLink 的问题
Problem with ForEach and NavigationLink in SwiftUI
这是我遇到问题的基本代码片段:
import SwiftUI
struct ContentView: View {
var pets = ["Dog", "Cat", "Rabbit"]
var body: some View {
NavigationView {
List {
ForEach(pets, id: \.self) {
NavigationLink(destination: Text([=10=])) {
Text([=10=])
}
}
}
.navigationBarTitle("Pets")
}
}
我收到错误:
Failed to produce diagnostic for expression; please file a bug report
我在这里的目的是熟悉 NavigationLink,并在单击该项目时导航到仅显示文本的新页面。
如有任何帮助,我们将不胜感激。
这与您使用的 shorthand 初始值设定项有关。这些备选方案中的任何一个都可以工作:
ForEach(pets, id: \.self) {
NavigationLink([=10=], destination: Text([=10=]))
}
ForEach(pets, id: \.self) { pet in
NavigationLink(destination: Text(pet)) {
Text(pet)
}
}
nicksarno 已经回答了,但既然你评论说你不明白,我会试一试。
$0 在未命名时引用当前闭包中的第一个参数。
ForEach(pets, id: \.self) {
// [=10=] here means the first argument of the ForEach closure
NavigationLink(destination: Text([=10=])) {
// [=10=] here means the first argument of the NavigationLink closure
// which doesn't exist so it doesn't work
Text([=10=])
}
}
解决办法是用<name> in
命名参数
ForEach(pets, id: \.self) { pet in
// now you can use pet instead of [=11=]
NavigationLink(destination: Text(pet)) {
Text(pet)
}
}
注意;你得到奇怪错误的原因是因为它找到了一个不同的 NavigationLink init,它确实有一个带参数的闭包。
这是我遇到问题的基本代码片段:
import SwiftUI
struct ContentView: View {
var pets = ["Dog", "Cat", "Rabbit"]
var body: some View {
NavigationView {
List {
ForEach(pets, id: \.self) {
NavigationLink(destination: Text([=10=])) {
Text([=10=])
}
}
}
.navigationBarTitle("Pets")
}
}
我收到错误:
Failed to produce diagnostic for expression; please file a bug report
我在这里的目的是熟悉 NavigationLink,并在单击该项目时导航到仅显示文本的新页面。
如有任何帮助,我们将不胜感激。
这与您使用的 shorthand 初始值设定项有关。这些备选方案中的任何一个都可以工作:
ForEach(pets, id: \.self) {
NavigationLink([=10=], destination: Text([=10=]))
}
ForEach(pets, id: \.self) { pet in
NavigationLink(destination: Text(pet)) {
Text(pet)
}
}
nicksarno 已经回答了,但既然你评论说你不明白,我会试一试。
$0 在未命名时引用当前闭包中的第一个参数。
ForEach(pets, id: \.self) {
// [=10=] here means the first argument of the ForEach closure
NavigationLink(destination: Text([=10=])) {
// [=10=] here means the first argument of the NavigationLink closure
// which doesn't exist so it doesn't work
Text([=10=])
}
}
解决办法是用<name> in
ForEach(pets, id: \.self) { pet in
// now you can use pet instead of [=11=]
NavigationLink(destination: Text(pet)) {
Text(pet)
}
}
注意;你得到奇怪错误的原因是因为它找到了一个不同的 NavigationLink init,它确实有一个带参数的闭包。