我试图在选中某个分组的单元格时,更改UITableView
中该分组的标题。由于应用程序已触发tableView:titleForHeaderInSection
,因此无法帮助解决此问题。我可以调用reloadData
,但性能受到影响,因为应用程序必须重新加载所有可见单元格。我还尝试使用自定义标头,但这也会导致一些性能问题。
是否有任何方法获取默认标头视图使用的UILabel
并手动更改其文本?
我试图在选中某个分组的单元格时,更改UITableView
中该分组的标题。由于应用程序已触发tableView:titleForHeaderInSection
,因此无法帮助解决此问题。我可以调用reloadData
,但性能受到影响,因为应用程序必须重新加载所有可见单元格。我还尝试使用自定义标头,但这也会导致一些性能问题。
是否有任何方法获取默认标头视图使用的UILabel
并手动更改其文本?
调用[tableView endUpdates]
可能会在不牺牲太多性能的情况下提供所需的结果。
[self.tableView beginUpdates];
[self.tableView endUpdates];
// forces the tableView to ask its delegate/datasource the following:
// numberOfSectionsInTableView:
// tableView:titleForHeaderInSection:
// tableView:titleForFooterInSection:
// tableView:viewForHeaderInSection:
// tableView:viewForFooterInSection:
// tableView:heightForHeaderInSection:
// tableView:heightForFooterInSection:
// tableView:numberOfRowsInSection:
使用:
[self.tableView headerViewForSection:i]
[self.tableView headerViewForSection:i].textLabel.text = [self tableView:self.tableView titleForHeaderInSection:i];
您将设置文本,但不会设置标签大小。您可以从NSString中获取所需的大小并自行设置:
[label.text sizeWithFont:label.font];
sizeWithFont
已经被弃用了。作为替代,您可以将标签的框架宽度设置为其父视图的宽度。 - Sergey M目前似乎没有任何标准API用于访问系统提供的节头视图。你尝试过更有针对性的reloadSections:withRowAnimation
来让UIKit显示新的节头文本吗?
你在使用自定义部分标题视图时遇到了什么样的性能问题?我怀疑标准标题视图仅仅是一个UILabel
而已。
UITableViewHeaderFooterView *sectionZeroHeader = [self.tableView headerViewForSection:0];
NSString *sectionZeroLabel = @"Section Zero";
[sectionZeroHeader.textLabel setText:[sectionZeroLabel uppercaseString]];
[sectionZeroHeader setNeedsLayout];
请务必告诉节标题视图需要布局,否则新文本可能会被截断。此外,部分标签通常都是大写字母。
由于UITableView不会对节头视图进行排队和出列以供重用,因此您可以考虑将所有节头视图存储在内存中。请注意,您将需要创建自己的带有背景等的节头视图来实现此目的,但这样做可以为您提供更多的灵活性和功能。
您还可以尝试标记节头视图(也需要您创建自己的节头视图),并根据需要从表格视图中获取它们。
tableView.headerView
。如果表头不可见,则返回nil,因此不会加载额外的表头。if let header = tableView.headerView(forSection: i) {
header.textLabel!.text = "new title"
header.setNeedLayout()
}
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
view.tag = section
// additional customization
}
func udpateVisibleSectionHeaders() {
for subview in tableView.subviews {
if let header = subview as? UITableViewHeaderFooterView {
let section = header.tag
header.textLabel!.text = "new title"
header.setNeedsLayout()
}
}
}
setNeedsLayout
,否则标签可能会被截断。for (UIView *v in self.tableView.subviews) {
// ... is this the one?
}
其中一种解决方案是管理外部数组,用于包含标签引用的多个部分标题,并在外部更新它们。
为了完整性,我们都在寻找的方法是这个私有API,它的名称正是你所期望的:
-(void)_reloadSectionHeaderFooters:withRowAnimation:
例如:
[tableView _reloadSectionHeaderFooters:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationAutomatic]
然而,我不建议使用这个。
tableView:viewForHeaderInSection:
和tableView:viewForFooterInSection:
没有被调用,因此您需要自己更改视图。 - Casper Zandbergen