I know how to change the height of the section headers in the table view. But I am unable to find any solution to change the default spacing before the first section.
Right now I have this code:
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
if (section == 0){
return 0;
}
return 10;
}
Return CGFLOAT_MIN
instead of 0 for your desired section height.
Returning 0 causes UITableView to use a default value. This is undocumented behavior. If you return a very small number, you effectively get a zero-height header.
Swift 3:
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 0 {
return CGFloat.leastNormalMagnitude
}
return tableView.sectionHeaderHeight
}
Swift:
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 0 {
return CGFloat.min
}
return tableView.sectionHeaderHeight
}
Obj-C:
- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
if (section == 0)
return CGFLOAT_MIN;
return tableView.sectionHeaderHeight;
}
If you use tableView
style grouped, tableView
automatically set top and bottom insets. To avoid them and avoid internal insets setting, use delegate methods for header and footer. Never return 0.0 but CGFLOAT_MIN
.
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
// Removes extra padding in Grouped style
return CGFLOAT_MIN;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
// Removes extra padding in Grouped style
return CGFLOAT_MIN;
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
// Removes extra padding in Grouped style
return CGFloat.leastNormalMagnitude
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
// Removes extra padding in Grouped style
return CGFloat.leastNormalMagnitude
}
This worked for me with Swift 4. Modify your UITableView
e.g. in viewDidLoad
:
// Remove space between sections.
tableView.sectionHeaderHeight = 0
tableView.sectionFooterHeight = 0
// Remove space at top and bottom of tableView.
tableView.tableHeaderView = UIView(frame: CGRect(origin: .zero, size: CGSize(width: 0, height: CGFloat.leastNormalMagnitude)))
tableView.tableFooterView = UIView(frame: CGRect(origin: .zero, size: CGSize(width: 0, height: CGFloat.leastNormalMagnitude)))
It appears that I can't set a table header view with height of 0. I ended up doing the following:
- (void)viewWillAppear:(BOOL)animated{
CGRect frame = self.tableView.tableHeaderView.frame;
frame.size.height = 1;
UIView *headerView = [[UIView alloc] initWithFrame:frame];
[self.tableView setTableHeaderView:headerView];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With