iOS-跑马灯效果

作者: FlyElephant | 来源:发表于2016-12-08 00:05 被阅读631次

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

  • (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;
    }`</code></pre>

效果:

FlyElephant.gif

相关文章

网友评论

    本文标题:iOS-跑马灯效果

    本文链接:https://www.haomeiwen.com/subject/gymjmttx.html