實現跑馬等效果,如果想要實現,頭部跟尾部同時出現在一個屏幕中的話,應該使用兩個 Label 比較好實現,于是有了以下思路.
@interface JDMarqueeView ()
@property (nonatomic,copy) NSString *msg; //需要展示的消息
@property (nonatomic,assign) CGFloat textW; //文字長度
@property (nonatomic,retain) UILabel *firstLabel; //跑馬燈的兩個 label
@property (nonatomic,retain) UILabel *secondLabel;
@end
@implementation JDMarqueeView
- (instancetype)initWithFrame:(CGRect)frame andMessage:(NSString *)message
{
self = [super initWithFrame:frame];
if (self) {
self.clipsToBounds =YES;
//為了兩個 label 不至于文字連在一起
_msg = [NSString stringWithFormat:@" %@ ",message];
[self createUI];
}
return self;
}
- (void)createUI {
_firstLabel =[JDUtils createLabelWithFrame:CGRectZero Font:14 Text:_msg];
_firstLabel.textAlignment =NSTextAlignmentLeft;
[_firstLabel sizeToFit];
//設置居中
_firstLabel.centerY =self.sizeHeight/2;
[self addSubview:_firstLabel];
_textW = _firstLabel.sizeWidth;
//如果文字長度大于控件寬度,則開始滾動
if (_textW>self.sizeWidth) {
_secondLabel =[JDUtils createLabelWithFrame:_firstLabel.frame Font:14 Text:_msg];
_secondLabel.textAlignment =NSTextAlignmentLeft;
_secondLabel.originX =CGRectGetMaxX(_firstLabel.frame);
[_secondLabel sizeToFit];
[self addSubview:_secondLabel];
[self startAnimation];
}
}
- (void)startAnimation
{
//計算走完一次需要的時間
NSInteger time = _msg.length / num;
[UIView animateWithDuration:time delay:0 options:UIViewAnimationOptionCurveLinear|UIViewAnimationOptionRepeat animations:^{
_firstLabel.originX =-_textW;
_secondLabel.originX = 0;
} completion:nil];
}
@end
雖然這個跑馬燈實現簡單,但是有幾點缺點
1.文字滾動初始位置必須是從View左側開始.
2.文字無法暫停
Demo地址:https://github.com/yuying2012/WJDStudyLibrary
這是一個大工程,請從工程中尋找相關模塊代碼.