动态更改静态单元格上的节标题文本

2024-01-19

我有一个 UITableViewController,其表视图具有静态单元格,在故事板中定义。

我的表格视图有两个部分。第一个部分有两个单元,第二个部分有三个单元。第二部分的标题中也有文本。

我想做的是,当用户点击第一部分中的第一个或第二个单元格时,更新第二部分的标题文本。动态地使用动态内容来执行此操作(假设日期和时间显示在他们点击单元格的那一刻)。

我尝试过很多事情,但是viewForHeaderSection只被调用一次。

我注册了标题部分单元格

tableView.registerClass(TableSectionHeader.self, forHeaderFooterViewReuseIdentifier: "secondSectionCell")

Where 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

最后一步是调用[self.tableView reload]修改后titleForSecondSection财产。或者,如果您不想重新加载整个表视图,只需调用- (void)reloadSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation

需要明确的是,在你的- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section,对于不需要更改标题的部分,只需返回一个静态字符串。对于需要更改标题的部分,返回您创建的动态属性。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

动态更改静态单元格上的节标题文本 的相关文章

随机推荐