Reputation: 1663
Hi all I am developing an app.I want to show a table view with a header view.When i navigate from Root view to Next view(tableview) which is as shown below.But my question is when i passes some text from root view to Next view(table view) as a header to next view it shows like the following in appropriate format.i need solution for this to show some better format.Following code that i used for this.
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
/* NSString *str_header1;
str_header1=[[NSString alloc]initWithString:@"Heading : "];
str_header1=[str_header1 stringByAppendingFormat:str_code1];
str_header1=[str_header1 stringByAppendingFormat:@" - "];
str_header1=[str_header1 stringByAppendingFormat:str_header]; */
// Create label with section title
UILabel *tmpTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 15, 300, 20)];
UILabel *titleLabel = tmpTitleLabel;
titleLabel.font = [UIFont boldSystemFontOfSize:12];
titleLabel.numberOfLines = 0;
titleLabel.textColor = [UIColor colorWithRed:0.30 green:0.34 blue:0.42 alpha:1.0];
titleLabel.shadowColor = [UIColor whiteColor];
titleLabel.shadowOffset = CGSizeMake(0.0, 1.0);
titleLabel.backgroundColor=[UIColor clearColor];
titleLabel.lineBreakMode = UILineBreakModeWordWrap;
titleLabel.text = str_combine;
//Calculate the expected size based on the font and linebreak mode of label
CGSize maximumLabelSize = CGSizeMake(300,9999);
expectedLabelSize= [str_combine sizeWithFont:titleLabel.font constrainedToSize:maximumLabelSize lineBreakMode:titleLabel.lineBreakMode];
//Adjust the label the the new height
CGRect newFrame = titleLabel.frame;
newFrame.size.height = expectedLabelSize.height;
titleLabel.frame = newFrame;
// Create header view and add label as a subview
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(10, 0, 320, expectedLabelSize.height+30)];
[view addSubview:titleLabel];
return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection: (NSInteger)section
{
return expectedLabelSize.height+30;
}
Upvotes: 0
Views: 1181
Reputation: 10754
Your code assumes that -tableView:viewForHeaderInSection:
is always called before -tableView:heightForHeaderInSection:
but that is not the case. You could move the size calculation to -tableView:heightForHeaderInSection:
to fix that.
Even better, as you seem to use only one table header view: There is a property on UITableView
called tableHeaderView
which you can use. Rename your method - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
to -(UIView *)headerView
, delete the method -tableView:heightForHeaderInSection:
and add the following line at the end of the view controller's -viewDidLoad
method:
self.tableView.tableHeaderView = [self headerView];
Upvotes: 2