Self Scrollable text inside CAScrollLayer

2019-01-15 23:01发布

问题:

I want to have text inside of a CAScrollLayer scroll by itself from starting point to ending point and then reset the animation. However I cannot seem to get a CATextLayer inside of a Scroll layer. I have even attempted to create a UILabel and use its layer as a sublayer to the scroll layer.

Here is the non working code. I do not know what the culprit is or what I am missing.

 UILabel *sampleText = [[UILabel alloc] init];

sampleText.font = [UIFont systemFontOfSize:20];

sampleText.text = @"Hello World";



[sampleText sizeToFit];

[scrollLayer addSublayer:sampleText.layer];


//add scroll layer to view controllers view
[self.view.layer addSublayer:scrollLayer];

Here is my try with CATextLayer

CATextLayer *numberLayer = [CATextLayer layer];
[numberLayer setFont:@"Helvetica-Neue"];
[numberLayer setFrame:CGRectMake(0, 0, 20, 30)];
[numberLayer setString:@"Hello Wolrd"];
[numberLayer setAlignmentMode:kCAAlignmentCenter];
[numberLayer setForegroundColor:[[UIColor blackColor] CGColor]];
numberLayer.zPosition = 99;

[scrollLayer addSublayer:numberLayer];

[self.view.layer addSublayer:scrollLayer]

回答1:

One hardly needs or wants a CAScrollLayer or a CATextLayer for this. Simply start with a superview that clips to its bounds, and inside that put a UILabel. Animate the sideways movement of the label and you're done.

Here's a rough sketch:

    let w1 = self.lab.frame.width
    let w2 = self.lab.superview!.frame.width
    let w = w1 - w2
    let x = self.lab.frame.origin.x
    UIView.animateWithDuration(5, delay: 0, options: .CurveLinear, animations: {
        self.lab.frame.origin.x -= w
        }, completion: {
            _ in
            self.lab.frame.origin.x = x
    })