Creating a multi-line UILabel to start text on top not middle

I have a little problem with multi-line UILabel, my UILabel text as starting in the middle is weird, and it rises when new lines appear, so the last line is always in the middle. I want it to behave like a regular text, starting from the top and lines that go under each other, the first line remains at the top. Sorry, if I explain it badly, I can try to develop if necessary! Thanks in advance!

+5
source share
2 answers

You can use the method sizeWithFont:constrainedToSize:lineBreakMode:for NSString to determine the height of a block of text based on font and limited width. Then you would update the frame of your label so that it is large enough to cover the text.

CGSize textSize = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(label.frame.size.width, MAXFLOAT) lineBreakMode:label.lineBreakMode];
label.frame = CGRectMake(20.0f, 20.0f, textSize.width, textSize.height);
+11
source

Since the sizeWithFont method is canceled in iOS 7.0 +, you can use an alternative method called boundingRectWithSize .

Example:

NSDictionary *attrsDictionary =[NSDictionary dictionaryWithObject:YourFont forKey:NSFontAttributeName];
NSAttributedString *attrString =[[NSAttributedString alloc] initWithString:yourString attributes:attrsDictionary];

textRect = [attrString boundingRectWithSize:yourSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];
0
source