我们还可以通过纯粹的动画来达到这种效果,上篇是通过计时器移动scrollView的content位置来达成效果的
#import "LBScrollSubtitleViewController.h"
@interface LBScrollSubtitleViewController ()
@property (nonatomic, strong) UILabel* textLabel;
@end
@implementation LBScrollSubtitleViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.textLabel = [[UILabel alloc] init];
[self.textLabel setFrame:CGRectMake(0, 0, 250, 35)];
[self.textLabel setCenter:self.view.center];
[self.view addSubview:self.textLabel];
NSString* text = @"Night gathers, and now my watch begins. It shall not end until my death. ";
[self.textLabel setText:text];
[self startAnimationIfNeeded];
}
- (void)startAnimationIfNeeded
{
[self.textLabel.layer removeAllAnimations];
CGSize textSize = [self.textLabel.text sizeWithFont:self.textLabel.font];
CGRect iFrame = self.textLabel.frame;
//保持高度不变,宽度设置成文字的大小的宽度
iFrame.size.width = textSize.width;
self.textLabel.frame = iFrame;
const float oriWidth = 180.0;
if (textSize.width > oriWidth)
{
NSLog(@"text width : %f", textSize.width);
//取180的差值
float offset = textSize.width - oriWidth;
NSLog(@"offset :%f", offset);
[UIView animateWithDuration:10 delay:0 options:UIViewAnimationOptionRepeat |
UIViewAnimationOptionCurveLinear
animations:^{
self.textLabel.transform = CGAffineTransformMakeTranslation(-offset, 0);
} completion:^(BOOL finished){ }];
}
}
@end
这种实现一个相当的坏处就是进入后台之后回来应用的动画效果就停止了,但是也有相当多的方法来解决。