There is no way of doing this using the tableView:titleForHeaderInSection:
method.
You need to use tableView:viewForHeaderInSection:
which is a UITableViewDelegate
method and return a UILabel
with the attributedText
set
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
NSString *title = @"";
title = @"Top Line \n";
if(_favouriteLocations.count == 0){
title = [title stringByAppendingString:@"Smaller font Bottom Line"];
}
NSMutableAttributedString *attString =[[NSMutableAttributedString alloc] initWithString:title];
NSRange range = [title rangeOfString:@"Smaller"];
[attString setAttributes:@{NSFontAttributeName:@"8"} range:NSMakeRange(range.location, title.length - range.location)];
UILabel *titleLabel = [UILabel new];
titleLabel.attributedText = attString;
return titleLabel;
}
If you've got a lot of sections you could also use the newer UITableViewHeaderFooterView
class and dequeue that. That view has a textLabel
property and just like above you could set the attributedText
on that. Its a bit more code but more efficient as you then don't return a newly created view each time.
static NSString *const HeaderCellId = @"header_id";
-(void)viewDidLoad
{
[super viewDidLoad];
// Setup table view
[tableView registerClass:[UITableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:HeaderCellId];
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
NSString *title = @"";
title = @"Top Line \n";
if(_favouriteLocations.count == 0){
title = [title stringByAppendingString:@"Smaller font Bottom Line"];
}
NSMutableAttributedString *attString =[[NSMutableAttributedString alloc] initWithString:title];
NSRange range = [title rangeOfString:@"Smaller"];
[attString setAttributes:@{NSFontAttributeName:@"8"} range:NSMakeRange(range.location, title.length - range.location)];
UITableViewHeaderFooterView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderCellId];
view.textLabel.attributedText = attString;
return view;
}
EDIT:
As noted by @PabloRomeu in the comments tableView:viewForHeaderInSection:
only works if tableView:heightForHeaderInSection:
is implemented returning a non-zero value.
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return 80;
}