Reputation: 2611
I'm working with an old Objective-C project which has not any storyboard. I need a UITableView
to display the result with UITableViewCell
that contains 3 labels. The task is to align 3 labels vertically in the UITableviewCell
Here is my Label initiation:
serviceTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 10, 200, LONG_MAX)];
[serviceTitleLabel setFont:[UIFont SingPostRegularFontOfSize:16.0f fontKey:kSingPostFontOpenSans]];
[serviceTitleLabel setNumberOfLines:0];
[serviceTitleLabel setTextColor:RGB(51, 51, 51)];
[serviceTitleLabel setBackgroundColor:[UIColor clearColor]];
[serviceTitleLabel setTextAlignment:NSTextAlignmentLeft];
[contentView addSubview:serviceTitleLabel];
statusLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 30, 200, 30)];
[statusLabel setFont:[UIFont SingPostBoldFontOfSize:12.0f fontKey:kSingPostFontOpenSans]];
[statusLabel setTextColor:RGB(125, 136, 149)];
[statusLabel setBackgroundColor:[UIColor clearColor]];
[contentView addSubview:statusLabel];
costLabel = [[UILabel alloc] initWithFrame:CGRectMake(216, 20, 85, 30)];
costLabel.right = contentView.right - 15;
[costLabel setFont:[UIFont SingPostBoldFontOfSize:16.0f fontKey:kSingPostFontOpenSans]];
[costLabel setTextColor:RGB(51, 51, 51)];
[costLabel setTextAlignment:NSTextAlignmentRight];
[costLabel setBackgroundColor:[UIColor clearColor]];
[contentView addSubview:costLabel];
How can we adjust in UITableViewController
so that the size will resize according to the label size? Need to set up in both cell and tableview? Any help is much appreciated. Thanks.
This is the screen now. Look not right
Upvotes: 0
Views: 1938
Reputation: 11127
You have to use UITableViewAutomaticDimension
to manage the cell height as per the content. For that you have to set the constraint of your labels from all the sides, ie Click on the PIN and then uncheck the Constraint from margin
check box and for both of your labels add constraints from Top, bottom, Left and Right side.As it is required if you want to use UITableViewAutomaticDimension
.
Now in the ViewController
in viewDidLoad
method add this two line
self.tableView.estimatedRowHeight = 44.0;
self.tableView.rowHeight = UITableViewAutomaticDimension;
Upvotes: 2
Reputation: 861
The solution depends on your iOS deployment target. If it's higher or equal than iOS 8 than:
self.tableView.rowHeight = UITableViewAutomaticDimension;
This solution works if constraints in cell set properly.
If it's lower than you need to calculate it by yourself, implement UITableViewDelegate
- tableView:heightForRowAtIndexPath:
Upvotes: 1