[英]How to animate the height changing of a header in section of a tableview?
[英]Changing UITableView section header without tableView:titleForHeaderInSection
当我选择该部分的单元格时,我正在尝试更改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]
您可以获取Section i的视图,然后手动“更新”它
如果您的视图只是自动生成的标签,这甚至可以工作,但您必须自己调整大小。 所以,如果你试图:
[self.tableView headerViewForSection:i].textLabel.text = [self tableView:self.tableView titleForHeaderInSection:i];
您将设置文本,但不会设置标签大小。 你可以从NSString获得所需的大小来自己设置:
[label.text sizeWithFont:label.font];
似乎没有任何标准API可用于访问系统提供的节标题视图。 你有没有尝试过更有针对性的reloadSections:withRowAnimation
让UIKit显示新的标题文本?
您在自定义部分标题视图中看到了哪些性能问题? 我怀疑标准的不只是UILabel
。
您可以直接设置节标题标题的标题。 例如,要设置零部分的标题:
UITableViewHeaderFooterView *sectionZeroHeader = [self.tableView headerViewForSection:0];
NSString *sectionZeroLabel = @"Section Zero";
[sectionZeroHeader.textLabel setText:[sectionZeroLabel uppercaseString]];
[sectionZeroHeader setNeedsLayout];
请确保告诉部分标题视图它需要布局,否则新文本可能会被截断。 部分标签通常都是大写的。
由于UITableView不会将节标题视图排入队列并将其取消以便重用,因此您还可以查看是否可以将所有节标题视图存储在内存中。 请注意,您必须使用背景等创建自己的节标题视图,但这样可以让您获得更多的灵活性和功能。
您还可以尝试标记节标题视图(还需要您创建自己的节标题视图),并根据需要从tableview中获取它们。
其中一个解决方案是管理包含标签引用的多个节头的外部数组,并在外部更新它们。
这是一个WAG,我可以想到很多原因,为什么它可能不起作用,但你不能遍历子视图,找到你正在寻找的那个? 例如
for (UIView *v in self.tableView.subviews) {
// ... is this the one?
}
为了完整起见,我们都在寻找的方法是这个私有API,它的命名完全符合您的期望:
-(void)_reloadSectionHeaderFooters:withRowAnimation:
例如:
[tableView _reloadSectionHeaderFooters:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationAutomatic]
但是,我不建议使用它。
如果你想只更新一个部分,最好的方法是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
或标签可以被截断。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.