CATextLayer不滚动

时间:2011-12-20 15:22:24

标签: iphone catextlayer

我目前正在编写一个应用程序,该应用程序读入文件并将标题放入列表中。单击每个标题时,它会切换到带有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的偏移以编程方式完成。对于某些辅助函数(CAScrollLayerscrollToPoint)以及稍微整洁的计算集,它可以子层次为scrollToRectCAScrollLayer还要求程序员处理触摸事件,因此为了简单起见,我不会追求这条路线。

对于那些希望使用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];

1 个答案:

答案 0 :(得分:0)

你是如何使用contentsRect的?它是一个单位矩形坐标,即每个参数介于0和1之间(包括)。

因此,如果您想在30,30点显示50 x 50子矩形,您可以

textLayer.contentsRect = CGRectMake(30.0f / CONTENT_WIDTH, 30.0f / CONTENT_HEIGHT, 267.0f / CONTENT_WIDTH, 320.0f / CONTENT_HEIGHT);

CONTENT_WIDTH和CONTENT_HEIGHT是内容的大小。