How to use UITableViewHeaderFooterView?

后端 未结 9 2048
傲寒
傲寒 2020-12-23 02:12

Hi I want to use UITableHeaderFooterView in my app and i am doing this:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional          


        
9条回答
  •  不思量自难忘°
    2020-12-23 02:30

    This is an old post and has good answers, but I wanted to share another work-around for a very similar issue I experienced.

    At first, I used:

    -(UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
    

    With a custom prototype cell for my header view. Subclassing UITableViewCell as such

        static NSString *cellIdentifier = @"CustomHeaderCell";
    CustomHeaderCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    

    However, when animating TableView cells above section headers (making them twice as tall) the header view would disappear. This, as pointed out, is because the implementation only supplied a view, not a re-usable view.

    Instead of forgoing everything with the customized prototype cell, I implemented the UITableViewHeaderFooterWithIdentifier and set it as the prototyped cell's contentView, without subclassing UITableViewHeaderFooterWithIdentifier.

      static NSString *customHeaderViewIdentifier = @"CustomHeaderView";
    UITableViewHeaderFooterView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:customHeaderViewIdentifier];
    
    headerView = (UITableViewHeaderFooterView *)cell.contentView;
    

    I realize this creates two instances of the header view (at least I think it would..) however it does allow you to keep the benefits of a customized prototype cell without doing everything programatically.

    Full code:

      // viewDidLoad
        [myTableView registerClass:[UITableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:@"CustomHeaderView"];
    
    // Implement your custom header
     -(UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
    {
         static NSString *cellIdentifier = @"CustomHeaderCell";
        CustomHeaderCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
        static NSString *customHeaderViewIdentifier = @"CustomHeaderView";
        UITableViewHeaderFooterView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:customHeaderViewIdentifier];
    
    // do your cell-specific code here
    // eg. cell.myCustomLabel.text = @"my custom text"
    
        headerView = (UITableViewHeaderFooterView *)cell.contentView;
    
    return headerView;
    }
    

提交回复
热议问题