Robert J. Clegg
Robert J. Clegg

Reputation: 7370

uilabel sizetofit doesn't work uitableviewcell

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.

Upvotes: 0

Views: 1818

Answers (1)

ganeshIOS
ganeshIOS

Reputation: 136

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.

Upvotes: 1

Related Questions