Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UILabel with dynamic width - Horizontal Alignment

I have an UILabel in a custom cell class in an UITableView and I use the following code to increase the width of the label dynamically in regards of its content:

CGSize sizeToMakeLabel = [cell.cellResult.text sizeWithFont:cell.cellResult.font];

cell.cellResult.frame = CGRectMake(cell.cellResult.frame.origin.x, cell.cellResult.frame.origin.y, sizeToMakeLabel.width, sizeToMakeLabel.height);

The problem that appears using the above code, is that I can no longer have the label to be right aligned (increase the width of it to the left instead of right).

If I don't use the above code and set alignment to right in IB, the alignment works. But in this case, I lose the dynamic width.

I've tried with:

cell.cellResult.textAlignment = UITextAlignmentRigth;
cell.cellResult.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;

but nothing happens.

Can someone help me out on this one please ?

like image 604
Razvan Avatar asked Aug 01 '26 21:08

Razvan


2 Answers

You can't right align the label because you set its real width for its frame.

If you want it to be dynamic but right aligned, you can do something like:

CGSize sizeToMakeLabel = [cell.cellResult.text sizeWithFont:cell.cellResult.font];

cell.cellResult.frame = CGRectMake(cell.cellResult.frame.origin.x + cell.cellResult.frame.size.width - sizeToMakeLabel.width, cell.cellResult.frame.origin.y, sizeToMakeLabel.width, sizeToMakeLabel.height);
like image 66
iSofTom Avatar answered Aug 04 '26 09:08

iSofTom


That's because you change the origin of the label when setting it's frame:cell.cellResult.frame.origin.x,

You could change the bounds to manage the width only.

like image 23
Nikita Pestrov Avatar answered Aug 04 '26 11:08

Nikita Pestrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!