How to remove the blank space at the top of a grouped UITableView?

后端 未结 8 1109
南旧
南旧 2020-12-08 20:12

When you create a UITableView with the UITableViewStyleGrouped style, it adds quite a lot of space in between the actual tableviewcells and the bor

8条回答
  •  萌比男神i
    2020-12-08 20:48

    This answer comes quite late, but I hope it helps someone.

    The space is there because of the UITableView's tableHeaderView property. When the the tableHeaderView property is nil Apple defaults a view. So the way around this is to create an empty view with a height greater than 0. Setting this overrides the default view thereby removing the unwanted space.

    This can be done in a Storyboard by dragging a view to the top of a tableView and then setting the height of the view to a value of 1 or greater.

    Or it can be done programmatically with the following code:

    Objective-C:

    CGRect frame = CGRectZero;
    frame.size.height = CGFLOAT_MIN;
    [self.tableView setTableHeaderView:[[UIView alloc] initWithFrame:frame]];
    

    Swift:

    var frame = CGRect.zero
    frame.size.height = .leastNormalMagnitude
    tableView.tableHeaderView = UIView(frame: frame)
    

    Comments

    As others have noted you can use this same solution for footers.


    Sources and Acknowledgements

    See the Documentation for more details on the tableHeaderView property.

    Thanks to @liushuaikobe for verifying using the least positive normal number works.

提交回复
热议问题