重新加载tableView部分而不重新加载标题部分 – Swift
我正在尝试重新加载tableView部分而不是重新加载整个tableview,因为我在标题部分有一个文本字段,当我调用self.tableView.reloadData()
我的键盘关闭。
我已经尝试了下面的代码,但是Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'attempt to delete row 5 from section 2 which only contains 4 rows before the update'
我得到此错误Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'attempt to delete row 5 from section 2 which only contains 4 rows before the update'
所以请问我的问题在哪里?
let newCount = self.placeArray.count var newIndexPaths = NSMutableArray(capacity: newCount) for var i = 0 ; i < newCount ; i++ { var indexPath = NSIndexPath(forRow: i, inSection: 2) newIndexPaths.addObject(indexPath) } self.tableView.beginUpdates() self.tableView.reloadRowsAtIndexPaths(newIndexPaths as [AnyObject], withRowAnimation: UITableViewRowAnimation.None) self.tableView.endUpdates()
您可以使用UITableView
的reloadSections
方法。
tableView.reloadSections(NSIndexSet(index: 2), withRowAnimation: .None)
Swift 3.0.1:
let sectionIndex = IndexSet(integer: 0) tableView.reloadSections(sectionIndex, with: .none) // or fade, right, left, top, bottom, none, middle, automatic
Swift 3.1 Xcode 8.3.3答案:)
问题是 – 每个部分当然包括标题,所以部分是:
section = header + footer + rows
答案是 – 由IndexPath直接重新加载行。 例:
-
假设你的表中有1个部分和用作表的数据源的“数组”:
let indexes = (0..
-
现在我们已经有了要重新加载的单元格索引数组,所以:
tableView.reloadRows(at: indexes, with: .fade)
我不知道为什么错误的答案会得到这么多的赞成。
注意:
-
UITableView.reloadData()
将重新加载所有表。 关于reloaddata的文档重新加载用于构造表的所有数据,包括单元格,节页眉和页脚,索引数组等。 为了提高效率,表视图仅重新显示可见的行。 如果表因重新加载而缩小,它会调整偏移量。 表视图的委托或数据源在希望表视图完全重新加载其数据时调用此方法。
-
UITableView.reloadSections(_ sections: IndexSet, with animation: UITableViewRowAnimation)
将重新加载特定的部分( 包括部分标题和部分页脚 )。 关于reloadsections的文档 -
UITableView.reloadRows(at indexPaths: [IndexPath], with animation: UITableViewRowAnimation)
将重新加载指定的行。 有关reloadRows的文档
所以这里reloadSections
在这里reloadSections
。 如果你的标题部分数据和状态没有改变,那么调用这个方法就不会有任何差异。
解决方案:使用reloadRows
加载所有部分或特定部分的行。 注意:此处您可以加载可见行,滚动查看时将加载其他行。 您还可以参考一节中的获取所有indexPaths以获取更多解决方案
var indexPaths = self.tableView.indexPathsForVisibleRows /* just roload visible rows of specified section indexPaths = indexPaths.filter({ (indexPath) -> Bool in return indexPath.section == SECTION_INDEX_NEED_TO_RELOAD }) */ self.tableView.reloadRows(at: indexPaths!, with: .none)