如何以编程方式向 UITableview 添加新部分?
我有分页,当我尝试在 PerformBatchUpdates 中调用 insertSections 时,它第一次工作正常,但是当加载第二页 UITableview 时不会更新(没有错误,只是没有更新并且不调用完成块)。
private var periods = [PeriodHistoryModel]()
func fetchHistoryWith(models: [PeriodHistoryModel]) {
guard models.count > 0 else {
return
}
let newSectionsCount = models.count - periods.count
let lastPeriod = periods.count - 1 >= 0 ? periods.count - 1 : 0
var newRows: [IndexPath] = [IndexPath]()
var newSections: [IndexSet] = [IndexSet]()
let lastPeriodOldCount = periods.last?.sessions.count ?? 0
let lastPeriodNewCount = models[lastPeriod].sessions.count
let newSessionsCount = lastPeriodNewCount - lastPeriodOldCount
if lastPeriod >= 0 {>
for index in 0..<newSessionsCount {
newRows.append(IndexPath(row: lastPeriodOldCount + index, section: lastPeriod))
}
}
for index in 0..<newSectionsCount {
let newSectionIndex = periods.count + index
newSections.append(IndexSet(integer: newSectionIndex))
for rowIndex in 0..<models[newSectionIndex].sessions.count {
newRows.append(IndexPath(row: rowIndex, section: newSectionIndex))
}
}
periods = models
tableView.performBatchUpdates({
for index in 0..<newSections.count {
tableView.insertSections(newSections[index], with: .none)
}
tableView.insertRows(at: newRows, with: .none)
})
}
reloadData不适合需要顺利进行
重击规则是“在执行批量更新之前更新表视图模型”。我刚刚创建了一个简单的项目并且运行良好。因此,请确保您的委托方法 numberOfSections 返回更新后的模型的计数。
我的项目如下。
class MyViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var numberOfSections: Int = 1
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func insertSectionTapped(_ sender: Any) {
numberOfSections += 1
let indexSet = IndexSet(integer: numberOfSections - 1)
tableView.performBatchUpdates({
tableView.insertSections(indexSet, with: .none)
}) { (update) in
print("Update SUccess")
}
}
@IBAction func insertRowTapped(_ sender: Any) {
}
}
extension MyViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return numberOfSections
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell.init(style: .default, reuseIdentifier: "DefaultId")
cell.textLabel?.text = "This is Section \(indexPath.section) - Row \(indexPath.row)"
return cell
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)