首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CATextLayer的线路数?

CATextLayer的线路数?
EN

Stack Overflow用户
提问于 2017-12-12 12:43:15
回答 1查看 1.8K关注 0票数 1

我的CATextlayer只支持一行,否则文本会被剪切。

试图设置像UILabel行为这样的文本内容..。有可能吗?

  1. 设置“行数”
  2. 通过静态 CATextLayer帧调整文本大小

代码语言:javascript
复制
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];
EN

回答 1

Stack Overflow用户

发布于 2017-12-12 18:00:50

你的问题就在这条线上,[text_layer setFrame:CGRectMake(0,0,200,50)];。我不认为一个CATextLayer本身能够容纳多行代码。它只会重新绘制文本,以在层的边界内进行包装。尝试根据设置的文本调整文本层的框架。您可以创建一个UILabel实例,以计算具有字包装的多行文本的框架,并将其设置为您的CATextLayer实例。

下面是一个UILabel类别,用于计算带有单词包装的多行文本的文本大小:

代码语言:javascript
复制
@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获取大小。就像这样:

代码语言:javascript
复制
// 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];
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47772963

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档