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

前端 未结 9 2427
暗喜
暗喜 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:40

    Updated Matthew Thomas's code for cell margins calculation. Created via UITableView's category. This can be useful, when you need to determine text height in cell, and you dont' know width of that cell.

    So, actual cell can be calculated like

    cell.width = tableView.width - tableView.cellsMargin * 2;
    

    An here's the code

    @implementation UITableView (CellsMargins)
    
    // This is black magic
    // from
    // http://stackoverflow.com/questions/4708085/how-to-determine-margin-of-a-grouped-uitableview-or-better-how-to-set-it
    
    - (CGFloat)cellsMargin {
    
       // No margins for plain table views
       if (self.style == UITableViewStylePlain) {
          return 0;
       }
    
       // iPhone always have 10 pixels margin
       if (! isIPad()) {
          return 10;
       }
    
       CGFloat tableWidth = self.frame.size.width;
    
       // Really small table
       if (tableWidth <= 20) {
          return tableWidth - 10;
       }
    
       // Average table size
       if (tableWidth < 400) {
          return 10;
       }
    
       // Big tables have complex margin's logic
       // Around 6% of table width,
       // 31 <= tableWidth * 0.06 <= 45
    
       CGFloat marginWidth  = tableWidth * 0.06;
       marginWidth = MAX(31, MIN(45, marginWidth));
       return marginWidth;
    }
    
    @end
    

提交回复
热议问题