CATextLayer wrapped sizeToFit?

橙三吉。 提交于 2019-12-05 03:26:04

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;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!