动态更改静态单元格上的节标题文本
我有一个UITableViewController,其表视图具有静态单元格,在故事板中定义。
我的表视图有两个部分。 第一个有两个单元,第二个有三个单元。 第二部分的标题中也有文字。
我想要做的是当用户点击第一部分中的第一个或第二个单元格时,更新第二部分的标题文本。 动态地使用动态内容(比如在点击单元格时显示日期和时间)。
我尝试过很多东西,但是viewForHeaderSection
只被调用一次。
我注册了标题部分单元格
tableView.registerClass(TableSectionHeader.self, forHeaderFooterViewReuseIdentifier: "secondSectionCell")
TableSectionHeader
的简单地说:
class TableSectionHeader: UITableViewHeaderFooterView { }
然后我可以动态设置节标题,如下所示:
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if section == 1 { if let cell = tableView.dequeueReusableHeaderFooterViewWithIdentifier("secondSectionCell") { cell.textLabel?.text = "hello world" return cell } } return nil }
我也实现了以下覆盖,因为有些人建议在实现viewForHeaderInSection
,它也是必需的:
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 40.0 }
即便如此。 viewForHeaderInSection
只被调用一次。
我可以以某种方式动态刷新节标题文本,如上所述?
您可以使用传统的表格视图方式轻松实现此目的。
即使它是静态的UITableView,在你的dataSource视图控制器中,你仍然可以实现- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
那么你如何动态更新标题? 为此视图控制器创建一个属性,例如NSString *titleForSecondSection
。 每当用户点击第一部分中的单元格时,您只需要在回调中更新此属性- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
最后一步是在修改titleForSecondSection
属性后调用[self.tableView reload]
。 或者如果您不想重新加载整个表视图,只需调用- (void)reloadSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation
要清楚,在你的- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
,对于不需要更改标题的部分,只需返回一个静态字符串。 对于需要更改标题的部分,返回您创建的动态属性。
只有在重新加载tableview时才会调用viewForHeaderInSection。 因此,假设您不想重新加载整个tableview,您可能需要直接更改标签的内容。 伪代码如:
var label_first_section_header //as global variable
然后在viewForHeaderInSection中将其指向标签
if section == 1 { if let cell = tableView.dequeueReusableHeaderFooterViewWithIdentifier("secondSectionCell") { cell.textLabel?.text = "hello world" label_first_section_header = cell.textLabel return cell } }
然后您可以随时动态更改文本,例如在didSelectRowAtIndexPath中