How to determine margin of a grouped UITableView (or better, how to set it)?

前端 未结 9 2439
暗喜
暗喜 2020-12-07 17:48

The grouped UITableView places a margin between the edge of the view and the table cells. Annoyingly (for me) this margin is some function of the width of the view.

9条回答
  •  不知归路
    2020-12-07 18:21

    I have tried a different approach. But not sure whether it always work. I had a grouped UITableView and needed to make customized Header View. But as you know, when implementing viewForHeader inSection method we can not determine the margins for our created view. So, what I have done is firstly add a CGRect property to ViewController .m file:

    @property(nonatomic)CGRect groupedCellRectangle;
    

    and in UITableViewDelegate:

    -(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
        static BOOL groupFrameInitialized = NO;
        if(!groupFrameInitialized){
            groupFrameInitialized = YES;
            self.groupedCellRectangle = cell.contentView.frame;
        }
    }
    

    after then, in my viewForHeader inSection method:

    -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
      UIView *v = [[UIView alloc] initWithFrame:CGRectMake(self.groupedCellRectangle.origin.x, 0, self.groupedCellRectangle.size.width, 28)];
      [v setBackgroundColor:[UIColor clearColor]];
      UILabel *label = [[UILabel alloc] initWithFrame:v.frame];
      label.text = @"KAF";
      [v addSubview:label];
      return v;
    }
    

    the result is as I assumed. groupedCellRectangle had successfully stored CGRect value with margin.

    The idea behind this approach was UITableView always call viewForHeader method after willDisplay call.

    Hope that helps...

提交回复
热议问题