CATextLayer行数?

时间:2017-12-12 12:43:15

标签: objective-c calayer catextlayer

我的CATextlayer仅支持1行 否则文字会被删除。

尝试设置UILabel行为等文本内容......是否可能?

  1. 设置“行数”

  2. 通过静态 CATextLayer框架调整文字大小

  3. enter image description here

    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];
    

1 个答案:

答案 0 :(得分:0)

你的问题就在这一行,[text_layer setFrame:CGRectMake(0,0,200,50)];。我不认为CATextLayer可以自行设置多条线路。它只会重新绘制文本以包含在图层的边界内。尝试根据正在设置的文本调整文本图层的框架。您可以创建一个UILabel实例,以计算包含自动换行的多行文字的框架,并将其设置为CATextLayer实例。

这里有一个UILabel类别来计算包含自动换行的多行文字的文字大小:

@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获取大小。像这样:

// 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];