我使用以下代码在tableView上调用批量更新(开始/结束更新):
let oldImageSet = Set(oldImageArray)
let newImageSet = Set(self.images)
let missingImages = newImageSet.subtracting(oldImageSet)
let missingImageIndexPaths = Array(missingImages).map{NSIndexPath(row: self.images.index(of: $0)!, section: 0)}
//Array(missingImages).map{NSIndexPath(forRow:newImageUUIDArray.indexOf($0)!,inSection:1)}
let removedImages = oldImageSet.subtracting(newImageSet)
let removedImageIndexPaths = Array(removedImages).map{NSIndexPath(row:oldImageArray.index(of: $0)!,section:0)}
self.tableView.beginUpdates()
if missingImageIndexPaths.isEmpty == false {
self.tableView.insertRows(at: missingImageIndexPaths as [IndexPath],with:.top)
}
if removedImageIndexPaths.isEmpty == false {
self.tableView.deleteRows(at: removedImageIndexPaths as [IndexPath],with:.none)
}
self.tableView.endUpdates()
哪个工作正常。
修改
这是我的tableView部分计数以及我如何设置它:
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 55
}
func numberOfSections(in tableView: UITableView) -> Int {
return posts.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
但现在我有另一个tableView我想能够打电话给它,但它有' Sections'所以当我使用它时,我会崩溃......?
有没有人知道如何在带有部分的tableView上使用此代码?
非常感谢提前!
答案 0 :(得分:1)
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 55
}
func numberOfSections(in tableView: UITableView) -> Int {
return posts.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
用以下代码替换代码:
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 55
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
答案 1 :(得分:0)
您应该将您对行执行的操作应用于部分,这意味着将IndexPath
更改为IndexSet
。可以使用IndexSet
个数组初始化Int
,其中每个Int
代表相应的部分。
let oldImageSet = Set(oldImageArray)
let newImageSet = Set(self.images)
let addedImages = newImageSet.subtracting(oldImageSet)
// map each image to the section equivalent to its index in `self.images`
let addedImageSections = Array(missingImages).map{ self.images.indexOf($0)! }
let addedImageIndexSet = IndexSet(addedImageSections)
// repeat above process but in reverse to find images that have been removed
let removedImages = oldImageSet.subtracting(newImageSet)
let removedImageSections = Array(removedImages).map{ oldImageArray.index(of: $0)! }
let removedImageIndexSet = IndexSet(removedImageSections)
self.tableView.beginUpdates()
// if images have been added insert new sections
if !addedImageIndexSet.isEmpty {
self.tableView.insertSections(addedImageIndexSet, with: .top)
}
// if images have been deleted remove sections
if !removedImageIndexSet.isEmpty {
self.tableView.deleteSections(removedImageIndexSet, with: .none)
}
self.tableView.endUpdates()