动态更改静态单元格

时间:2017-02-09 03:06:53

标签: ios swift uitableview tableviewcell

我有一个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只被调用一次。

我能够以某种方式动态刷新节标题文本,如上所述吗?

2 个答案:

答案 0 :(得分:0)

您可以使用传统的表格视图轻松实现此目的。

即使它是静态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中,对于不需要更改标题的部分,只需返回一个静态字符串即可。对于需要更改标题的部分,请返回您创建的动态属性。

答案 1 :(得分:0)

只有在重新加载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

相关问题