简体   繁体   中英

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:

在此处输入图片说明

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.

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. ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM