0

我目前正在编写一个读取文件并将标题放入列表的应用程序。当单击每个标题时,它会切换到一个带有 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对于一些辅助函数(scrollToPointscrollToRect)和稍微整洁的计算集, 它可以被子分层。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];
4

1 回答 1

0

你是如何使用内容矩形的?这是一个单位矩形坐标,即每个参数都介于零和一(包括)之间。

所以如果你想在点 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 是内容的大小。

于 2011-12-20T20:18:47.843 回答