我目前正在编写一个应用程序,它可以读取文件并将标题放入列表中。当单击每个标题时,它切换到一个带有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的文档和其他许多问题,但没有找到我要找的东西。
编辑:这个类是可以滚动的,但是它需要以编程的方式使用contentsRect的偏移量来完成。对于一些辅助函数(scrollToPoint和scrollToRect),它可以被子层次化到CAScrollLayer,以及稍微整洁的计算集合。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];发布于 2011-12-20 20:18:47
你是如何使用contentsRect的?它是一个单位矩形坐标,即每个参数在0到1之间(包括在内)。
所以如果你想在30点上显示50x50个子矩形,你可以这样做
textLayer.contentsRect = CGRectMake(30.0f / CONTENT_WIDTH, 30.0f / CONTENT_HEIGHT, 267.0f / CONTENT_WIDTH, 320.0f / CONTENT_HEIGHT);其中CONTENT_WIDTH和CONTENT_HEIGHT是内容的大小。
https://stackoverflow.com/questions/8577694
复制相似问题