Why does tableVieW:viewForHeaderInSection ignore the frame property of my UILabel?
Solution 1
That's because the UITableView automatically sets the frame of the header view you provide to
(0, y, table view width, header view height)
y
is the computed position of the view and
header view height
is the value returned by tableView:heightForHeaderInSection:
Solution 2
Maybe it's better do add a subview:
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
let label = UILabel(frame: CGRect(x: 15, y: 5, width: tableView.frame.width, height: 20))
label.text = "\(sections[section].year)"
view.addSubview(label)
return view
}
![phi](https://i.stack.imgur.com/L8Czb.png?s=256&g=1)
phi
Senior (almost 40 years old!) iOS Engineer, trying to be helpful.
Updated on June 04, 2022Comments
-
phi about 2 years
Basically I want to change the font and the color of my section header, so I implement
tableVieW:viewForHeaderInSection
. First I tried this code:-(UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { UILabel* headerLabel = [[[UILabel alloc] init] autorelease]; headerLabel.frame = CGRectMake(10, 0, 300, 40); headerLabel.backgroundColor = [UIColor clearColor]; headerLabel.textColor = [UIColor blackColor]; headerLabel.font = [UIFont boldSystemFontOfSize:18]; headerLabel.text = @"My section header"; return headerLabel; }
but for some reason the frame property is ignored (I'm talking about the 10px inset on the left). Now I use the following:
-(UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { UIView* headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)] autorelease]; UILabel* headerLabel = [[UILabel alloc] init]; headerLabel.frame = CGRectMake(10, 0, 300, 40); headerLabel.backgroundColor = [UIColor clearColor]; headerLabel.textColor = [UIColor blackColor]; headerLabel.font = [UIFont boldSystemFontOfSize:18]; headerLabel.text = @"My section header"; [headerView addSubview:headerLabel]; [headerLabel release]; return headerView; }
with the desired results. Can someone explain to me why the second approach works and the first doesn't?
PS. In both cases I implement
tableView:heightForHeaderInSection
as well, returning 40.0 -
phi over 13 yearsThen I really need the "headerView" in my code in order to get this inset, right?
-
Bogatyr over 13 yearsIt would also work to just prepend some spaces in front of the text in the label, that's a good trick for quick UILabel adjustment.
-
Koolala almost 11 yearsThis behaves differently in iOS 7 for my case. It's adding 1 pt padding to both sides of the headerView in iOS 7. Do you guys see the same?