2017-02-09 70 views
1

我有一个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 
    } 

我也实施了以下重写,因为有些人建议t当执行viewForHeaderInSection时,还需要:

override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { 
    return 40.0 
} 

即使如此。 viewForHeaderInSection只被调用一次。

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

+1

你不能这样做它。没有这方面的官方文件。你需要做自定义方法,如:http://stackoverflow.com/questions/23501952/refresh-only-the-custom-header-views-in-a-uitableview,但是,我强烈建议你离开节标题单独使用细胞,而不是每个部分的第一个细胞。除非你想做一些你需要的粘性标题或其他东西。 – 2017-02-09 03:18:18

+0

@Sneak我喜欢你的建议。可能是最简单的方法。唯一的事情是摆弄桌面视图来处理分隔单元格的线条,以及它们如何从tableview的左边缘插入。 – dbarros

+0

tableView.reloadSections将重新加载页眉(和页脚)以及该部分的内容 – Dale

回答

0

实际上,您可以使用传统的表格视图方式轻松实现此目的。

即使是静态的UITableView,在您的数据源视图控制器,你仍然可以实现- (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中,对于不需要更改标题的部分,只需返回一个静态字符串即可。对于需要更改标题的部分,返回您创建的动态属性。

+0

对不起,我只注意到你在使用Swift。应该在Swift中发布。但它是一样的想法。希望能帮助到你。 :) – Elvin

0

viewForHeaderInSection只会在tableview被重新加载时调用。所以假设你不想重新加载整个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方法