iOS-跑马灯效果

iOS中跑马灯实现由两种一种是通过UIView的动画,第二种是通过UIScrollView实现,最简单的通过UIView的线性动画即可实现:

- (void)scrollAnimation {
    CGRect mainRect = [[UIScreen mainScreen] bounds];
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, mainRect.size.width, 100)];
    bgView.backgroundColor = [UIColor redColor];
    [self.view addSubview:bgView];
    self.scrollText = @"FlyElephant--博客--http://www.jianshu.com/users/24da48b2ddb3/latest_articles";
    CGFloat width = [self textWidth:self.scrollText];
    self.testLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,60,width,30)];
    self.testLabel.backgroundColor = [UIColor clearColor];
    self.testLabel.text = self.scrollText;
    [bgView addSubview:self.testLabel];
    [self linearAnimation];
}

- (void)linearAnimation {
    CGRect frame = self.testLabel.frame;
    [UIView animateWithDuration:3 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        self.testLabel.frame = CGRectMake(-frame.size.width, frame.origin.y, frame.size.width, frame.size.height);
    } completion:^(BOOL finished) {
        CGRect mainRect = [[UIScreen mainScreen] bounds];
        CGFloat width = [self textWidth:self.scrollText];
        self.testLabel.frame = CGRectMake(mainRect.size.width, 60, width, 30);
        [self linearAnimation];
    }];
}

- (CGFloat)textWidth:(NSString *)text {
    CGSize size = [text boundingRectWithSize:CGSizeMake(MAXFLOAT, 20) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14.0f]} context:nil].size;
    return size.width;
}

效果:

iOS-跑马灯效果_第1张图片
FlyElephant.gif

你可能感兴趣的:(iOS-跑马灯效果)