美文网首页
swift:Collection数据删除多个数据

swift:Collection数据删除多个数据

作者: 成为_5995 | 来源:发表于2020-04-08 11:02 被阅读0次

问题:

在使用UICollectionView时,经常会碰到删除多个cell的问题。问题可归结为:二元数组中删除多个数据。

struct VideoModel {

    let path: String

}

var collection = [[VideoModel]]()

删除方法:

func delete(indexPaths: [IndexPath]) {}

简单暴力的方法:新建集合,过滤要删除的

    var newCollection = [[VideoModel]]()    

    for section in (0..<videoCollection.count) {      

        var videos = videoCollection[section]      

        if indexPaths.first(where: { $0.section == section }) == nil {        

            newCollection.append(videos)        

            continue      

        }      

        for row in (0..<videos.videos.count) {        

            if indexPaths.first(where: { $0.row == row }) != nil { continue }        

            videos.append(videos[row])      

        }    

    }    

    videoCollection = newCollection

占位法:利用option特性,将删除的部分设置为nil,过滤

var collection = [[VideoModel?]?]()    

indexPaths.forEach { (indexPath) in      

    collection[indexPath.section]?[indexPath.item] = nil    

}         

collection = collection.map { (items) -> [VideoModel?]? in      

    items?.filter { $0 != nil }    

}

排序法:删除由大到小

indexPaths.sorted { $0 > $1 }.forEach { collection[$0.section].remove(at: $0.item) }

相关文章

网友评论

      本文标题:swift:Collection数据删除多个数据

      本文链接:https://www.haomeiwen.com/subject/xthnphtx.html