从表格视图中删除单元格后更新 indexPath.row [英] Updating indexPath.row after deleting a cell from table view
问题描述
我有一个表格视图,其中的单元格在点击时呈现不同的表格视图,根据 indexPath,即:
I have a table view with cells that present a different table view when tapped on, according to the indexPath, i.e.:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let nc = UINavigationController()
let productController = ProductController()
nc.viewControllers = [productController]
//Apple
if (indexPath.row == 0) {
productController.navigationItem.title = "Apple Products";
}
//Google
if (indexPath.row == 1) {
productController.navigationItem.title = "Google Products";
}
//Twitter
if (indexPath.row == 2) {
productController.navigationItem.title = "Twitter Products";
}
//Tesla
if (indexPath.row == 3) {
productController.navigationItem.title = "Tesla Products";
}
//Samsung
if (indexPath.row == 4) {
productController.navigationItem.title = "Samsung Products";
}
present(nc, animated: true, completion: nil)
}
但是当我像这样删除一个单元格时......
However when I delete a cell like so....
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath)
{
if editingStyle == .delete
{
tableView.beginUpdates()
CompanyController.companies.remove(at: indexPath.row)
CompanyController.logos.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
tableView.endUpdates()
}
}
....indexPath 未更新,因此如果我删除 Apple 单元格(在 indexPath.row 0),Google 单元格会取代它的位置,但仍会指向 Apple 产品页面,依此类推其余的公司.我认为 tableView.delete rows 行正在处理这个问题,但事实并非如此.删除某些内容后如何更新 indexPath?
....the indexPath isn't updated, so if I delete the Apple cell (at indexPath.row 0), the Google cell takes its place, but still leads to the Apple products page, and so on and so forth for the rest of the companies. I figured the tableView.delete rows line was taking care of that, but it's not. How can I update the indexPath once something is deleted?
推荐答案
不要对数据进行硬编码并假设特定的行.将数据放入数组中,并根据索引路径从数组中获取值.当一行被删除时,通过从数组中删除来更新你的数据模型.
Don't hardcode data and assume specific rows. Put the data into an array and get the values from the array based on the index path. When a row is deleted, update your data model by deleting from the array.
将您的 didSelectRow
方法更新为:
Update your didSelectRow
method to:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let nc = UINavigationController()
let productController = ProductController()
nc.viewControllers = [productController]
productController.navigationItem.title = CompanyController.companies[indexPath.row]
present(nc, animated: true, completion: nil)
}
这篇关于从表格视图中删除单元格后更新 indexPath.row的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!