简体   繁体   中英

UITableView - Section header. How to change text?

I have a project which uses Storyboards. I have a UITableView with Static cells and Group style.

I need to change the section text in one section depending on which selection is made in a segmented control (in another section)

I have found some solutions which indicate that you should use override this method:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

and trigger an update by calling:
[[self tableView]reloadSections:[NSIndexSet indexSetWithIndex:SectionToChange] withRowAnimation:UITableViewRowAnimationFade];

The problem is when I call reloadSections then all the rows and cells in the section in question get deleted. The text updates correctly thought but with this unwanted side effect.

I think I found the answer here: Changing UITableView section header without tableView:titleForHeaderInSection

It may not be very elegant but it seams to work.

I can trigger an update to only the section header with none of the unwanted side effects by calling: [self.tableView headerViewForSection:1].textLabel.text = [self tableView:self.tableView titleForHeaderInSection:1];

So the only thing needed is to implement:

- (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;
}

If you have implemented these functions then removing them should fix your problem:

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM