Transition animation gone when presenting a NavigationLink in SwiftUI

喜你入骨 提交于 2020-08-10 23:11:28

问题


I have a List with 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())

And a corresponding ViewModel which stores the selected item's id.

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

The problem is that when I use NavigationLink(destination:tag:selection:) the transition animation is gone - the child view pops up immediately. When I use NavigationLink(destination:) it works normally, but I can't use it because I need to perform some action when a NavigationLink is selected.

Why the transition animation is gone? Is this a problem with NavigationLink(destination:tag:selection:)?


回答1:


You could put your action inside the NavigationLink. This should solve your animation problem:

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:


It turned out to be a problem with .id(UUID()) at the end of the list. Removing it restores the transition animation:

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

I added this following this link How to fix slow List updates in SwiftUI. Looks like this hack messes up tags/selections when using NavigationLink(destination:tag:selection:).



来源:https://stackoverflow.com/questions/61988298/transition-animation-gone-when-presenting-a-navigationlink-in-swiftui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!