Reputation: 383
In my App (iPad) there was a need to create a UITableView that contained a number of columns. To do this I had to create a custom UITableViewCell to provide the columns needed.
Now, it's time to place headers on these columns. In the 'viewForHeaderInSection' delegate I want to placed a label that spreads the width of the table.
All has gone well, the Background colour has been set and that reaches out to the width of the view nicely.
But when I go to use:
label.text = [NSString stringWithFormat:@" Date Dist Litres Cost($)"];
I don't get the text spreading out to represent the above example. What I get is more like:
" Date Dist Litres Cost($)"
How do I restore the spaces I need in the Header Text?
Upvotes: 2
Views: 5083
Reputation: 1498
Well i don't know what you are trying to do and whats the purpose and sure it looks peculiar. But just to get spaces inside a string in objective-c, you can simply add "\t" and it will add space equal to a TAB.
label.text = [NSString stringWithFormat:@"Date \t Dist \t Litres \t Cost($)"];
This will added spaces in your string but better way is to use different headers for different columns and set their header titles, as suggested by the other answers
Upvotes: 2
Reputation: 90117
You should create a header view that has four UILabel subViews.
Something like this:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
// 4 * 69 (width of label) + 3 * 8 (distance between labels) = 300
UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(10, 4, 69, 22)];
label1.text = @"Date";
[headerView addSubview:label1];
UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(87, 4, 69, 22)];
label2.text = @"Dist";
[headerView addSubview:label2];
UILabel *label3 = [[UILabel alloc] initWithFrame:CGRectMake(164, 4, 69, 22)];
label3.text = @"Litres";
[headerView addSubview:label3];
UILabel *label4 = [[UILabel alloc] initWithFrame:CGRectMake(241, 4, 69, 22)];
label4.text = @"Cost($)";
[headerView addSubview:label4];
return headerView;
}
Adjust colors, fonts and frames to your requirements.
This will be much cleaner than relying on the width of the space character.
Your way will work if you use a fixed width font, but I would suggest against it.
When you want to localise your app into different languages the task of counting spaces will become a nightmare.
Upvotes: 5
Reputation: 10172
It will be good if you do it by adding labels in UIView
(let's call headerView
) to it's appropriate position, and make alignment of all labels NSTextAlignmentCenter
then set label titles accordingly. Then return that headerView
.
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
Upvotes: 1