问题描述
我的CATextlayer仅支持1行
,否则文本将被剪切。
My CATextlayer support only 1 lineotherwise the text is cut.
试图设置UILabel行为之类的文本内容...有可能吗?
trying to set text content like UILabel Behaviour... is it possible?
-
设置行数
set "number of lines"
调整文本通过静态 CATextLayer框架
adjust text size by static CATextLayer frame
CATextLayer *text_layer= [[CATextLayer alloc] init];
[text_layer setBackgroundColor:[UIColor clearColor].CGColor];
[text_layer setBackgroundColor:[UIColor blueColor].CGColor];
[text_layer setForegroundColor:layers.textColor.CGColor];
[text_layer setAlignmentMode:kCAAlignmentCenter];
[text_layer setBorderColor:layers.borderColor.CGColor];
[text_layer setFrame:CGRectMake(0,0,200,50)]; //note: frame must be static
[text_layer setString:@"thank you for your respond"];
text_layer.wrapped = YES;
[text_layer setAlignmentMode:kCAAlignmentCenter];
推荐答案
您的问题是这行, [text_layer setFrame:CGRectMake(0,0,200,50)];
。我认为CATextLayer不会布局以容纳多行。它只会重新绘制文本以包装在图层范围内。尝试根据设置的文本调整文本层的框架。您可以创建一个 UILabel
实例,以计算带有换行的多行文本的框架,并将其设置为您的 CATextLayer
Your problem is this line right here, [text_layer setFrame:CGRectMake(0,0,200,50)];
. I don't think a CATextLayer would lay itself out to accommodate multiple lines. It will only re-draw the text to wrap within the layer's bounds. Try adjusting your text layer's frame based on the text being set. You can create a UILabel
instance, to calculate the frame for having multiline text with word wrapping and set it to your CATextLayer
instance.
这里是 UILabel
类别,用于使用换行计算多行文本的文本大小:
Here's a UILabel
category to calculate text size for multiline text with word wrapping:
@interface UILabel (Height)
- (CGSize)sizeForWrappedText;
@end
@implementation UILabel (Height)
- (CGSize)sizeForWrappedText {
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.bounds.size.width, CGFLOAT_MAX)];
label.numberOfLines = 0;
label.font = self.font;
label.text = self.text;
[label sizeToFit];
return label.frame.size;
}
@end
创建 UILabel
实例,并使用 sizeForWrappedText
来获取大小。像这样:
Create a UILabel
instance, and use the sizeForWrappedText
to get the size. Something like this:
// Make sure the someFrame here has the preferred width you want for your text_layer instance.
UILabel *label = [[UILabel alloc] initWithFrame:someFrame];
[label setText:@"My awesome text!"];
CGRect frame = text_layer.frame;
frame.size = [label sizeForWrappedText];
[text_layer setFrame:frame];
这篇关于CATextLayer行数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!