带有文本字段绑定的 SwiftUI 列表 - 当文本字段聚焦时重新排序会变得混乱

发布于 2025-01-19 19:04:23 字数 1123 浏览 2 评论 0原文

我有一个代表带有书籍的数组的列表。 标题由文本字段显示,因此用户可以立即点击并编辑标题。

当我启用编辑模式并重新排序元素时,在将文本字段焦点集中时,它会弄乱列表行和绑定。 我认为这是一个错误,因为只有在向上移动列表时才发生。

编辑:

  • 我向苹果提交了一个错误报告。案例:FB9976702
  • 有人知道解决方法吗?

import SwiftUI

struct TextfieldList: View {

    @State var books = [
        Book(name: "Lord of the Rings"),
        Book(name: "Harry Potter"),
        Book(name: "War and Peace")
    ]

    var body: some View {
        NavigationView{
            List{
                ForEach($books) { $book in
                    TextField(book.name, text: $book.name)
                }
                .onMove(perform: move)
            }
            .toolbar {
                EditButton()
            }
        }
    }

    func move(from source: IndexSet, to destination: Int) {
        books.move(fromOffsets: source, toOffset: destination)
    }

}

struct Book: Identifiable {
    var id = UUID()
    var name: String
}

I have a list which represents an array with book titles.
The title is displayed by a textfield so the user can tap in and edit the title right away.

When I enable edit mode and reorder the elements, while a textfield is focused, it messes up the list rows and bindings.
I assume it's a bug as it only happens when moving list rows upwards.

Edit:

  • I filed a bug report to Apple. Case: FB9976702
  • Does someone know a workaround?

enter image description here

import SwiftUI

struct TextfieldList: View {

    @State var books = [
        Book(name: "Lord of the Rings"),
        Book(name: "Harry Potter"),
        Book(name: "War and Peace")
    ]

    var body: some View {
        NavigationView{
            List{
                ForEach($books) { $book in
                    TextField(book.name, text: $book.name)
                }
                .onMove(perform: move)
            }
            .toolbar {
                EditButton()
            }
        }
    }

    func move(from source: IndexSet, to destination: Int) {
        books.move(fromOffsets: source, toOffset: destination)
    }

}

struct Book: Identifiable {
    var id = UUID()
    var name: String
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文