When you create a UITableView
with the UITableViewStyleGrouped
style, it adds quite a lot of space in between the actual tableviewcells and the bor
Single line solution:
Objective-C
self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, CGFLOAT_MIN)];
Swift
self.tableView.tableHeaderView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 0.0, height: Double(FLT_MIN)))
For iOS 11.0+
tableView.contentInsetAdjustmentBehavior = .never
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)
As others have noted you can use this same solution for footers.
See the Documentation for more details on the tableHeaderView
property.
Thanks to @liushuaikobe for verifying using the least positive normal number works.
Swift 5 onwards:
tableView.contentInsetAdjustmentBehavior = .never
Older Swift. Use it in the viewDidLoad()
method.
tableView.tableHeaderView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 0.0, height: Double.leastNormalMagnitude))
You need to set footer too
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
return 0;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
return [[UIView alloc] initWithFrame:CGRectZero];
}
If the style of your tableView is UITableViewStyleGrouped
, then you have to pay attention to the delegate of the height of SectionHeader or SectionFooter, cause this needs to be implemented right under this case.
The return value should not be 0, even if the SectionHeader or the height of SectionFooter is 0, it needs to be a very small value; try CGFLOAT_MIN
.
For my example:
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
if (section == [self.dataArray indexOfObject:self.bannerList]) {
return 46;
}
return CGFLOAT_MIN;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
return CGFLOAT_MIN;
}
Make sure you implemented these two methods, and the value is right, and the top margin will be fixed.