Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change UILabel width based on text length in iOS?

I want to display an image next to a 'UILabel', however 'UILabel' has variable text length, so I don't know where to place the image.

Image should move according to the size of the label.

How can I accomplish this?

like image 589
iOSNoob Avatar asked Dec 25 '22 03:12

iOSNoob


1 Answers

Although Keshav answer will work, it's deprecated

try:

NSDictionary *attributes = @{NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue" size:14]};

CGRect rect = [textToMeasure boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)
                                          options:NSStringDrawingUsesLineFragmentOrigin
                                       attributes:attributes
                                          context:nil];

Then use the Size of rect to determine your positioning and label size.

CGRect currentLabelFrame = self.label.frame;

currentLabelFrame.size.width = rect.size.width;

self.label.frame = currentLabelFrame;
like image 76
theiOSDude Avatar answered Dec 28 '22 10:12

theiOSDude