在SwiftUI列表中移动项目时不需要的动画 [英] Unwanted animation when moving items in SwiftUI list

查看:171
本文介绍了在SwiftUI列表中移动项目时不需要的动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个SwiftUI列表,如下面的示例代码所示.

I have a SwiftUI List like in the example code below.

struct ContentView: View {
    @State var numbers = ["1", "2", "3"]
    @State var editMode = EditMode.inactive

    var body: some View {
        NavigationView {
            List {
                ForEach(numbers, id: \.self) { number in
                    Text(number)
                }
                .onMove {
                    self.numbers.move(fromOffsets: $0, toOffset: $1)
                }
            }
            .navigationBarItems(trailing: EditButton())
        }
    }
}

当我进入编辑模式并将项目上移一个位置时,放下项目后会发生奇怪的动画(请参见下面的gif).看起来被拖动的项目返回到其原始位置,然后再次移动到目标位置(带有动画)

When I enter edit mode and move the item one position up the strange animation happens after I drop the item (see the gif below). It looks like the dragged item comes back to its original position and then moves to the destination again (with animation)

有趣的是,如果将项目拖动到列表的下方或向上拖动多个位置,则不会发生.

What's interesting it doesn't happen if you drag the item down the list or more than one position up.

我猜这是因为即使状态列表中的项目已经通过拖放方式在视图侧重新排序,但当状态中的项目重新排序时,列表也会执行动画.但是显然,除了将项目向上移动一个位置以外,它在所有情况下都能很好地处理它.

I guess it's because the List performs animation when the items in the state get reordered even though they were already reordered on the view side by drag and drop. But apparently it handles it well in all the cases other than moving item one position up.

关于如何解决此问题的任何想法?也许这是一个已知的错误?

Any ideas on how to solve this issue? Or maybe it's a known bug?

我正在使用XCode 11.4.1,构建目标是iOS 13.4

I'm using XCode 11.4.1 and the build target is iOS 13.4

(还请注意,在现实世界"应用中,我使用的是Core Data,并且在移动项目时,其顺序在数据库中进行了更新,然后在状态中进行了更新,但是动画的问题看起来完全相同. )

(Please also note that in the "real world" app I'm using Core Data and when moving items their order is updated in the DB and then the state is updated, but the problem with the animation looks exactly the same.)

推荐答案

这里是解决方案(已通过Xcode 11.4/iOS 13.4测试)

Here is solution (tested with Xcode 11.4 / iOS 13.4)

var body: some View {
    NavigationView {
        List {
            ForEach(numbers, id: \.self) { number in
                HStack {
                    Text(number)
                }.id(UUID())        // << here !!
            }
            .onMove {
                self.numbers.move(fromOffsets: $0, toOffset: $1)
            }
        }
        .navigationBarItems(trailing: EditButton())
    }
}

这篇关于在SwiftUI列表中移动项目时不需要的动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆