问题描述
如果我设置 textLayer.wrapped =是
,如何调整 textLayer
的大小以包含换行文本?即,如何获得 textLayer
的新高度?
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
?
基本上,我想要类似-[UILabel sizeToFit]
。
推荐答案
您需要做的第一件事就是获取
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
这将为您提供 CGSize
,然后您可以使用它来设置 UILabel
的框架或您正在使用的 UIView
的任何子类。
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.
因此,假设 textLayer
是 UILabel
-而不是 CALayer
-您最终会得到一些回报像这样:
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;
这篇关于CATextLayer包装了sizeToFit吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!