0

I have a UILabel that displays a user's "bio". I also have the user able to edit this text by having a uitextview pop up upon a user tap and then once the user is done adding or removing text from this uitextview, i say label.text = textview.text, so it updates the bio label's text.
However, I want a way of telling the label to fix it's height according to how much text was added or removed. Is there a way of doing this? Thank you in advance!

NathanF

Nathan Fraenkel
  • 3,422
  • 4
  • 18
  • 21

4 Answers4

4
CGRect labelFrame = label.frame;
labelFrame.size = [textview.text sizeWithFont:label.font
                            constrainedToSize:CGSizeMake(label.frame.size.width, CGFLOAT_MAX)
                                lineBreakMode:label.lineBreakMode];
label.frame = labelFrame;

This will resize the label (height) according to the new text (while respecting font and linebreakmode).

NOTE: UILineBreakMode has been deprecated as of 6.0. Use NSLineBreak instead.

Source

Alex
  • 1,233
  • 2
  • 17
  • 27
cweinberger
  • 3,518
  • 1
  • 16
  • 31
4

call

[labelName sizeToFit];

after setting the new text. Also make sure you set word wrap or character wrap like so:

[labelName setLineBreakMode:UILineBreakModeWordWrap];

or

[labelName setLineBreakMode:UILineBreakModeCharacterWrap];

Let me know if you have any other questions!

jacerate
  • 456
  • 3
  • 8
1

This method "sizeWithFont" is deprecated in iOS 7 instead of this you can use the method below:

CGRect rect = [YourText boundingRectWithSize:CGSizeMake(labelWidth, CGFLOAT_MAX)
                                       options:NSStringDrawingUsesLineFragmentOrigin
                                       context:nil];
 NSLog(@"Height: %f",rect.size.height);

For more info look into: Apple's Documentation

Prike
  • 57
  • 10
0

You can use [NSString sizeWithFont:...] to measure text for use in a label.

See also: How to get the size of a NSString

Community
  • 1
  • 1
Philippe Leybaert
  • 168,566
  • 31
  • 210
  • 223