CATextLayer wrapped sizeToFit?
Asked Answered
V

1

8

If I set textLayer.wrapped = YES, how do I resize textLayer to contain the wrapped text? I.e., how do I get the new height of the textLayer?

Basically, I want something like -[UILabel sizeToFit].

Vetiver answered 21/11, 2011 at 22:44 Comment(1)
was wondering about that too..Suction
B
2

The first thing you need to do is get the size of the text.

Thankfully, the NSString UIKit Additions Reference offers a method to do exactly that:

- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode

That will give you a CGSize that you can then use to set the frame of your UILabel or whatever subclass of UIView that you're using.

So, assuming textLayer is a UILabel - rather than a CALayer - you'll end up with something like this:

UIFont *myFont = [UIFont boldSystemFontOfSize:12.0f];
CGSize myFontSize = [myString sizeWithFont:myFont];
myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, myFontSize.width, myFontSize.height)];
myLabel.text = newTitle;
myLabel.font = myFont;
Brough answered 30/1, 2012 at 18:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.