项目满减规则很多,用一个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