ios跑马灯的label,简易版

项目满减规则很多,用一个UILabel展示可能显示不全,想要完全看到字就需要有跑马灯效果。

调用:

    AutoScrollLabel * autoLabel = [[AutoScrollLabel alloc] initWithFrame:CGRectMake(0, 100, 320, 50)];
    autoLabel.scrollSpeed = 80 ;
    // @"大弦嘈嘈如急雨,小弦切切如私语.嘈嘈切切错杂弹,大珠小珠落玉盘."
    // @"大弦嘈嘈如急雨."
    autoLabel.textLabel.text = @"大弦嘈嘈如急雨,小弦切切如私语.嘈嘈切切错杂弹,大珠小珠落玉盘." ;
    [autoLabel startScrollIfNeed];
    [self.view addSubview:autoLabel];
    

建2个文件,直接新建一个类叫AutoScrollLabel 继承自UIScrollView,然后复制下面内容到这个新类中即可.

.h 文件

#import <UIKit/UIKit.h>


@interface AutoScrollLabel : UIScrollView

/// 每秒移动多少像素
@property(nonatomic) float scrollSpeed;
/// 滚动到结束时,暂停多长时间
@property(nonatomic) NSTimeInterval pauseInterval;
@property (nonatomic,strong) UILabel * textLabel ;
/// 设置完textLabel.text调用
- (void)startScrollIfNeed ;

@end

.m文件

#import "AutoScrollLabel.h"

@implementation AutoScrollLabel


- (id)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super initWithCoder:aDecoder]) {

        [self commonInit];
    }
    return self;
    
}


- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
        [self commonInit];
    }
    return self;
}


- (void)commonInit {
    
    self.scrollSpeed = 80 ;
    self.pauseInterval = 3;
    
    self.scrollEnabled = NO ;
    
    self.textLabel = [[UILabel alloc] initWithFrame:self.bounds];
    
    [self addSubview:self.textLabel];

}

- (void)startScrollIfNeed {
    [self.textLabel sizeToFit] ;
    self.contentSize = self.textLabel.bounds.size ;
    
    // 需要滚动
    if (self.textLabel.bounds.size.width>self.bounds.size.width) {
        [self animationScroll];
    }
    
    
}
- (void)animationScroll {
    
    self.contentOffset = CGPointMake(-self.bounds.size.width, 0);
    
    [UIView animateWithDuration:self.textLabel.frame.size.width/self.scrollSpeed delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        
        self.contentOffset = CGPointMake(self.textLabel.frame.size.width - self.bounds.size.width, 0);

    } completion:^(BOOL finished) {
        
        [self performSelector:@selector(animationScroll) withObject:nil afterDelay:self.pauseInterval];
        
    }];
    
    
}

@end

demo: https://github.com/guochaoshun/AutoScrollLabel , 补充了2种方式, 一种使用动画, 一种使用CADisplayLink

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值