Lê Khánh Vinh Lê Khánh Vinh - 3 months ago 9
iOS Question

Objective C setup auto row height in code

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

enter image description here

Answer

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;
Comments