How to hide a section in UITableView?

前端 未结 12 2199
梦如初夏
梦如初夏 2020-12-05 00:32

There are some section in the table that does not contain any data and would like to hide that section.

How to do this?

12条回答
  •  再見小時候
    2020-12-05 01:16

    If you return 0 for the height of the section, Apple API will ignore it. So just return a small value greater than 0.

    - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
      if (section == 0) {
        return 1;
      }
    
      return 44;
    }
    

    Also implement view for header and return nil for the section you don't want to show.

    - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
      if (section == 0 && !self.personaCells.count) {
        return nil;
      }
    
      UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 44)];
      UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 20, headerView.frame.size.width, 20)];
      NSString *headerTitle = @"SAMPLE TITLE";
      headerLabel.text = headerTitle;    
      [headerView addSubview:headerLabel];
      return headerView;
    }
    

提交回复
热议问题