swift 如何删除列表中的导航链接

bmp9r5qi  于 2022-11-28  发布在  Swift
关注(0)|答案(3)|浏览(142)

我的项目中有以下代码

@State private var selectedGenreID: Int64? = 0

@FetchRequest(entity: Genres.entity(), sortDescriptors: [NSSortDescriptor(key: "genName", ascending: true, selector: #selector(NSString.localizedStandardCompare))])
var genres: FetchedResults<Genres>

var body: some View {
    List(genres, id: \Genres.genID, selection: $selectedGenreID, rowContent: { genre in
        NavigationLink(genre.genName!, destination: GenreView(isNew: false, genre: genre))
    })
    .navigationBarTitle("Žánry")
    .navigationBarItems(trailing: NavigationLink(destination: GenreView(isNew: true), label: {Image(systemName: "plus.circle")}))
}

我想知道如何实现swipe来删除列表中每一行的功能。我知道应该通过.onDelete修饰符,但我不知道如何应用如上构造的List。如果List是通过ForEach创建的,它就可以工作。谢谢。

ccrfmcuu

ccrfmcuu1#

在列表中使用ForEach有什么问题?您只能在ForEach中使用.onDelete修饰符。在您的示例(没有ForEach的列表)中,一个列表包含一个单元格,其中包含所有导航链接,在您的示例中,应该使用.onDelete删除什么?
大概是这样的:

List {
        ForEach(genres, id:\Genres.genID) { genre in // here I don't know what your Genres.ID is so could be mistake
            NavigationLink(destination: GenreView(isNew: false, genre: genre)) {
                Text("\(genre.genName!)")
            }.simultaneousGesture(TapGesture().onEnded{
                // save selected id if you need
            })
        }.onDelete(perform: // your onDelete action here)
    }
ldxq2e6h

ldxq2e6h2#

这就是我最终成功的方法

List {
        ForEach(genres, id:\Genres.genID) { genre in
            NavigationLink(destination: GenreView(isNew: false, genre: genre)) {
                Text("\(genre.genName!)")
            }
        }
        .onDelete(perform: { indexes in
            for index in indexes {
                let genre = genres[index]
                //Handling of deletion
            }
        })
}
pkbketx9

pkbketx93#

您的示例:

var body: some View {
List(genres, id: \Genres.genID, selection: $selectedGenreID, rowContent: { genre in
    NavigationLink(genre.genName!, destination: GenreView(isNew: false, genre: genre))
})

修正示例:

var body: some View {
List {
ForEach(genres, id: \Genres.genID, selection: $selectedGenreID, rowContent: { genre in
    NavigationLink(genre.genName!, destination: GenreView(isNew: false, genre: genre))
})
}
    .onDelete(perform: deleteRow)

func deleteRow(at offsets: IndexSet) {
  ganres.remove(atOffsets: offsets)
}

仅列出(...更改为ForEach(...

相关问题