我目前正在编写一个读取文件并将标题放入列表的应用程序。当单击每个标题时,它会切换到一个带有 CATextLayer 的控制器,其中包含与该标题相关联的文本(通常是几个段落)。最初,我使用 UITextView,但我发现我需要更多格式选项(即对齐对齐)并切换到 CATextLayer。
我在这里阅读了其他问题,CATextLayer 天生就是可滚动的,但是我找不到如何触发该行为。当我尝试设置contentsRect
时,我的文本完全从视图中消失。
这是我的设置代码,除了滚动之外还可以使用:
CATextLayer *textLayer = [[CATextLayer alloc] init];
textLayer.alignmentMode = kCAAlignmentJustified;
textLayer.string = [_data objectForKey:@"Text"];
textLayer.wrapped = YES;
textLayer.frame = CGRectMake(27, 75, 267, 320);
textLayer.font = [UIFont fontWithName:@"Helvetica" size:17.0f];
textLayer.foregroundColor = [UIColor blackColor].CGColor;
textLayer.backgroundColor = [UIColor whiteColor].CGColor;
[textLayer setCornerRadius:8.0f];
[textLayer setMasksToBounds:YES];
[textLayer setBorderWidth:1.0f];
[textLayer setBorderColor:[UIColor grayColor].CGColor];
[self.view.layer addSublayer:textLayer];
[textLayer release];
我查看了 CATextLayer 和许多其他 SO 问题的文档,但没有找到我想要的东西。
编辑:这个类可以滚动,但是需要使用contentsRect
的偏移量以编程方式完成。CAScrollLayer
对于一些辅助函数(scrollToPoint
和scrollToRect
)和稍微整洁的计算集, 它可以被子分层。CAScrollLayer
还需要程序员处理触摸事件,所以为了简单起见,我不会走这条路线。
对于那些想用 . 走这条路的人CAScrollLayer
,我的设置代码更改为以下内容:
CAScrollLayer *scrollLayer = [[CAScrollLayer alloc] init];
scrollLayer.frame = CGRectMake(27, 75, 267, 320);
scrollLayer.backgroundColor = [UIColor whiteColor].CGColor;
scrollLayer.scrollMode = kCAScrollVertically;
[scrollLayer setCornerRadius:8.0f];
[scrollLayer setMasksToBounds:YES];
[scrollLayer setBorderWidth:1.0f];
[scrollLayer setBorderColor:[UIColor grayColor].CGColor];
scrollLayer.contentsRect = CGRectMake(0, 0, 250, 350);
scrollLayer.contentsGravity = kCAGravityCenter;
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
{
scrollLayer.contentsScale = [[UIScreen mainScreen] scale];
}
CATextLayer *textLayer = [[CATextLayer alloc] init];
textLayer.alignmentMode = kCAAlignmentJustified;
textLayer.string = [_notice objectForKey:@"Text"];
textLayer.wrapped = YES;
textLayer.frame = CGRectMake(5, 5, 250, 500);
textLayer.font = [UIFont fontWithName:@"Helvetica" size:17.0f];
textLayer.foregroundColor = [UIColor blackColor].CGColor;
textLayer.backgroundColor = [UIColor whiteColor].CGColor;
[scrollLayer addSublayer:textLayer];
[self.view.layer addSublayer:scrollLayer];
[scrollLayer release];
[textLayer release];