SwiftUI:删除后更新 NavigationView (iPad) [英] SwiftUI: Update NavigationView after deletion (iPad)
问题描述
我想在 iPad 上删除一行后显示 空视图(此处:Text("Please select a person.")
).
I want to show the empty view (here: Text("Please select a person.")
) after the deletion of a row has happend on an iPad.
当前:iPad 上的详细信息视图在删除项目后不会更新.预期:在所选项目被删除后显示空视图.
Currently: The detail view on an iPad will not get updated after the deletion of an item. Expected: Show the empty view after the selected item gets deleted.
struct DetailView: View {
var name: String
var body: some View {
Text("Detail of \(name)")
}
}
struct MainView: View {
@State private var users = ["Paul", "Taylor", "Adele"]
var body: some View {
NavigationView {
List {
ForEach(users, id: \.self) { user in
NavigationLink(destination: DetailView(name: user)) {
Text(user)
}
}
.onDelete(perform: delete)
}
Text("Please select a person.")
}
}
func delete(at offsets: IndexSet) {
users.remove(atOffsets: offsets)
}
}
NavigationView 示例来自 使用 Swift 进行黑客攻击.
NavigationView example from Hacking With Swift.
在下面的例子中,详细视图在第一次启动后正确显示:here一个>
In the example below, the detail view is shown correctly after the first launch: here
但是删除一行之后,之前选择的详细视图(这里:Paul
)仍然显示:这里
But after the deletion of a row, the previously selected detail view (here: Paul
) is still shown: here
推荐答案
从 iOS 14 开始,似乎不支持从导航视图的列表中删除元素.
As of iOS 14, deleting an element from a list in a navigation view does not seem to be supported.
NavigationLink
类型采用 isActive
绑定,但这在删除的情况下不起作用.当您收到 .onDelete
回调时,为时已晚.NavigationLink
不再在列表中,对传递给它的绑定的任何更改都不会产生任何影响.
The NavigationLink
type takes an isActive
binding, but that does not work in the case of deletion. When you receive the .onDelete
callback it is too late. That NavigationLink
is not in the list anymore and any change to the binding you passed to it is not going to have any effect.
解决方法是将所有元素的绑定传递给 DetailView
,以便它可以验证元素是否存在并相应地显示一些内容.
The workaround is to pass a binding to the DetailView
with all the elements, so that it can verify if an element is present and display some content accordingly.
struct DetailView: View {
var name: String
@Binding var users: [String]
var body: some View {
if users.contains(name) {
Text("Detail of \(name)")
} else {
EmptyView()
}
}
}
struct MainView: View {
@State private var users = ["Paul", "Taylor", "Adele"]
var body: some View {
NavigationView {
List {
ForEach(users, id: \.self) { user in
NavigationLink(destination: DetailView(name: user, users: $users)) {
Text(user)
}
}
.onDelete(perform: delete)
}
}
}
func delete(at offsets: IndexSet) {
users.remove(atOffsets: offsets)
}
}
这篇关于SwiftUI:删除后更新 NavigationView (iPad)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!