【问题标题】:Transition animation gone when presenting a NavigationLink in SwiftUI在 SwiftUI 中显示 NavigationLink 时过渡动画消失了
【发布时间】:2020-05-24 15:39:50
【问题描述】:

我有一个带有 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())

还有一个对应的 ViewModel 存储了选中项的 id。

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

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

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

【问题讨论】:

    标签: ios swift swiftui swiftui-navigationlink


    【解决方案1】:

    您可以将您的操作放在 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())
    

    【讨论】:

    • 谢谢。我赞成您的回答,尽管这是一种解决方法,而不是直接的解决方案。
    【解决方案2】:

    原来是列表末尾的.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
    

    我在此链接How to fix slow List updates in SwiftUI 之后添加了此内容。看起来这个 hack 在使用 NavigationLink(destination:tag:selection:) 时会弄乱标签/选择。

    【讨论】:

      猜你喜欢
      • 2021-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-01
      • 2021-11-29
      • 2021-01-12
      • 1970-01-01
      相关资源
      最近更新 更多