UITableView - 如何更改分区头部文本?

5
我有一个使用Storyboard的项目。我有一个静态单元格和分组样式的UITableView。
根据在另一个区段中所做的选择,需要更改一个区段的文本。
我已经找到了一些解决方案,指出应该使用覆盖此方法:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 并通过调用以下方法触发更新:
[[self tableView]reloadSections:[NSIndexSet indexSetWithIndex:SectionToChange] withRowAnimation:UITableViewRowAnimationFade]; 问题是,当我调用reloadSections时,该部分中的所有行和单元格都被删除。文本正确更新,但会产生这种不必要的副作用。

可能重复:https://dev59.com/CWkv5IYBdhLWcg3wkBoa#10505982 - Alladinian
@Alladinian链接的问题有一个更简洁的解决方案。只需覆盖numberOfSectionsInTableView:,将调用titleForSection,由于它是静态表格视图,因此您可以返回从故事板设计中知道的常数编号。 - GreatWiz
3个回答

11

我想我在这里找到了答案:不使用tableView:titleForHeaderInSection更改UITableView部分标题

可能不太优雅,但似乎可以工作。

通过调用以下代码,我可以触发仅针对部分标题的更新,而没有任何不需要的副作用:

[self.tableView headerViewForSection:1].textLabel.text = [self tableView:self.tableView titleForHeaderInSection:1];

因此,唯一需要实现的是:

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
   if (section == 1){
      if (self.segmentX.selectedSegmentIndex == 0) // or some condition
         return @"Header one";
      else
         return @"Header two";
  }
  return nil;
}

1
这是一个非常好的答案。就iOS 7.1.1而言,我已经成功地解决了这个问题。 - Bill Burgess
在iOS 8上,我从headerViewForSection中得到了nil返回值...为了解决这个问题,我只是缓存了我的代理创建的header视图,并引用了那些视图。 - CMash
如何将文本转换为小写。自动更改为大写。 - jose920405

-1
如果您已经实现了这些函数,那么删除它们应该可以解决您的问题:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

我目前正在实现cellForRowAtIndexPath函数。删除该函数并没有改变结果。在调用以下代码后,该部分中的所有行和单元格都被移除: [[self tableView]reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationFade]; 但是,该部分的标题正确地更改了。 - Ásgeir Gunnar Stefánsson
那么numberOfRowsInSection方法呢?在重新加载数据后,一定有一些基础控制方法告诉该部分没有任何单元格。 - Mike S
不,它不起作用。当我在相关部分调用[[self tableView]reloadSections:[NSIndexSet indexSetWithIndex:SectionToChange] withRowAnimation:UITableViewRowAnimationFade];时,行和单元格就会消失,只留下一个空的灰色空间。但是,部分标题会正确更改。 - Ásgeir Gunnar Stefánsson

-3
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{        if (section == 0)
          {
                lbl.text = @"abc";
          }
        if (section == 2)
          {
                lbl.text = @"2ndsectionbeigns";
          }
return headerview;

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接