在 SwiftUI 中呈现 NavigationLink 时过渡动画消失了

Transition animation gone when presenting a NavigationLink in SwiftUI

我有一个带有 NavigationLinks 的列表。

List {
    ForEach(items, id: \.id) { item in
        NavigationLink(destination: ItemView(), tag: item.id, selection: self.$viewModel.selectedItemId) {
            Text("Some text")
        }
    }
    .onDelete(perform: delete)
}
.id(UUID())

以及存储所选项目 ID 的相应 ViewModel。

class ViewModel: ObservableObject {
    @Published var selectedItemId: String? {
        didSet {
            if let itemId = selectedItemId {
                ...
            }
        }
    }
    ...
}

问题是,当我使用 NavigationLink(destination:tag:selection:) 时,过渡动画消失了 - 子视图立即弹出。当我使用 NavigationLink(destination:) 它正常工作,但我不能使用它,因为我需要在选择 NavigationLink 时执行一些操作。

为什么过渡动画没有了?这是 NavigationLink(destination:tag:selection:) 的问题吗?

您可以将您的操作放在 NavigationLink 中。这应该可以解决您的动画问题:

List {
    ForEach(items, id: \.id) { item in
        NavigationLink(destination: ItemView(), isActive: $isActive, tag: item.id, selection: self.$viewModel.selectedItemId) {
            EmptyView()
        }
        Button(action: {
            // The action you wand to have done, when the View pops.
            print("Test")
            self.isActive = true
        }, label: {
            Text("Some text")
        })
    }
    .onDelete(perform: delete)
}
.id(UUID())

原来是列表末尾的.id(UUID())有问题。删除它恢复过渡动画:

List {
    ForEach(items, id: \.id) { item in
        NavigationLink(destination: ItemView(), tag: item.id, selection: self.$viewModel.selectedItemId) {
            Text("Some text")
        }
    }
    .onDelete(perform: delete)
}
//.id(UUID()) <- removed this line

我在 link How to fix slow List updates in SwiftUI 之后添加了这个。在使用 NavigationLink(destination:tag:selection:).

时,看起来这个 hack 弄乱了 tags/selections