0

I have a custom UITableViewCell that has two UILabels that sit next to each other. I need the UILabel on the left to grow as it's text grows and the UILabel on the right of it it to move over to the right as this happens.

I am using Autolayout and have setup the constraints. However the UILabel on the left never fits the text it has. I have tried sizeToFit however this does;t do anything. Can someone tell me where I am going wrong?

I thought auto layout will grow the UILabels based on their intrinsic content sizes?

Edit

Here is what my cell looks like:

enter image description here

So the top left label has the following constraints:

Pinned to left / top edges. Width constraint Horizontal spacing to label to its right.

The label to its right has similar constraints too.

I need the UIImageView and the grey label to move to the right as the label on the far left grows.

Robert J. Clegg
  • 7,231
  • 9
  • 47
  • 99
  • sizeToFit wont work if Autolayout is enabled. Yo need to set your constraints instead – Pancho May 28 '14 at 11:46
  • I've tried it without auto layout and it still doesn't work. I will upload a picture now of the auto layout constraints. – Robert J. Clegg May 28 '14 at 11:47
  • If not mistaking `sizeToFit` will only decrease the width of your `UILabel`. You have to define size that is greater than the text length, or increase the number of lines. Set the text and call `sizeToFit`. You should do this every time you want to update your text as `sizeToFit` will never expand the `UILabel's` width – Pancho May 28 '14 at 11:52
  • All I need is the label to fit the text it contains. That is not happening. I assume once that works, the UILabel and UIImageView to its right will move as the constraints will change. – Robert J. Clegg May 28 '14 at 11:54

1 Answers1

1

The sizeToFit will only adjust itself within its given size. If the size of label is (100, 30) and if the text size comes to (30, 30) then it will change its size to (30, 30).

Now, if the size of label is (30, 30) and text size comes to (50, 30) then it will stick to the size allocated for it. In short it takes the minimum out of the text size and allocated size. i.e MIN(actualSize, textSize).

For getting the actual width required, you should use (NSString UIKit Additions):

 - (CGRect)   boundingRectWithSize:(CGSize)size 
                           options:(NSStringDrawingOptions)options 
                        attributes:(NSDictionary *)attributes 
                           context:(NSStringDrawingContext *)context;

And sorry to say but you need to do this every time you assign text to the label.

Example can be find in this @Shan's SO answer.

Community
  • 1
  • 1
ganeshIOS
  • 136
  • 2