0

我已经使用 CATextLayer 一起显示粗体和普通文本。现在有时我从 Web 服务响应中获取长文本,所以我无法显示完整的文本。任何人都可以帮我制作 CATextLayer 对象的方法像 textview 一样可滚动。请向我建议任何有关此的解决方案。我也参考了Here但它对我不起作用。我正在使用这段代码:

/* 按需创建文本层 */

if (!_textLayer) {
    _textLayer = [[CATextLayer alloc] init];
    //_textLayer.font = [UIFont boldSystemFontOfSize:13].fontName; // not needed since `string` property will be an NSAttributedString
    _textLayer.backgroundColor = [UIColor clearColor].CGColor;
    _textLayer.wrapped = YES;
    //CALayer *layer = self.navigationController.toolbar.layer; //self is a view controller contained by a navigation controller
    _textLayer.frame = CGRectMake(5,325, 310, 90);
    _textLayer.contentsScale = [[UIScreen mainScreen] scale]; // looks nice in retina displays too :)
    _textLayer.alignmentMode = kCAAlignmentJustified;
    _textLayer.masksToBounds = YES;
    [self.view.layer addSublayer:_textLayer];
}

在底部,我还尝试将我的 _textLayer 添加到 UITextView 的层,而不是 self.view.layer。

请建议我如何实现此功能?

4

2 回答 2

4

您可以将 CATextLayer 添加到 UIScrollView 并免费滚动。根据需要设置滚动视图的框架,并将 contentSize 设置为 CATextLayer 框架并将其添加到滚动层,如下所示(实际上不是工作代码):

UIScrollView* scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0,0,100,100)];
CATextLayer* layer = [CATextLayer layer];
//layer init code goes here
scroll.contentSize = CGSizeMake(1000,1000);//or your actual text layer size
[scroll.layer addSublayer:layer];

你就完成了!不要忘记将滚动添加为您的视图子视图。

于 2012-11-20T13:09:13.907 回答
0

使用 NSString 的方法sizeWithFont:constrainedToSize:获取给定字体的文本的边界矩形,然后使用此大小设置图层的框架:

NSString* myString = ....;
CGSize size =     [myString sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:CGSizeMake(100, 100)];
_textlayer.frame = CGRectMake(0,0,size.width,size.height);

只是不要忘记使用适当的字体/约束大小。

于 2012-11-21T08:32:17.013 回答