
跑馬燈的本質是:用 timer 每隔一段時間驅動 scrollView 的 contentOffset 往左偏移,視覺上就形成滾動。原理簡單,但細節決定成品品質——要兼顧流暢度與效能,有幾個地方必須處理好。
把可調參數都開成屬性,才能適應各種場景。
/* 初始化 */ -(instancetype)initWithFrame:(CGRect)frame textArray:(NSArray *)textArray colorArray:(NSArray *)textColorArray; // 字幕文字陣列 @property(nonatomic, strong) NSArray<NSString *> *textArray; // 字幕顏色陣列 @property(nonatomic, strong) NSArray<UIColor *> *textColorArray; // 畫布背景色 @property(nonatomic, strong) UIColor *backgroundColorOfCanvas; // 標籤背景圖 @property(nonatomic, strong) UIImage *backgroundImageOfCanvas; // 字級大小 @property(nonatomic, assign) CGFloat fontOfSize; // 定時器 @property(nonatomic, strong) NSTimer *timer;
思路和無限輪播圖相同:把同一份內容複製一份接在後面。當 scrollView 滾到「複製品」的起點時,把 contentOffset 拉回原始內容的起點。因為兩段內容完全相同,這個跳躍在視覺上察覺不到,於是就成了連續循環。
#pragma mark - 建立 scrollView 內容
-(void)createContentOfScrollView {
self.contentSize = CGSizeMake(0, self.bounds.size.height);
self.contentOffset = CGPointMake(0, 0);
self.showsHorizontalScrollIndicator = NO; // 隱藏指示條
CGFloat labelY = 0;
CGFloat labelW = 200;
CGFloat labelH = self.bounds.size.height;
// 同樣的內容放兩遍,即可無縫循環
for (int j = 0; j < 2; j++) {
for (int i = 0; i < self.textArray.count; i++) {
UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.contentSize.width, labelY, labelW, labelH)];
// 標籤背景
UIImageView *labelBackGroundView = [[UIImageView alloc] initWithFrame:textLabel.frame];
labelBackGroundView.image = self.backgroundImageOfCanvas;
// 文字內容,越界時給個佔位符
if (i < self.textArray.count) {
textLabel.text = self.textArray[i];
} else {
textLabel.text = @"----";
}
// 文字顏色,缺少對應顏色時退回預設值
if (i < self.textColorArray.count) {
textLabel.textColor = self.textColorArray[i];
} else {
textLabel.textColor = [UIColor blackColor];
}
textLabel.font = [UIFont systemFontOfSize:self.fontOfSize];
textLabel.tag = LABEL_TAG_INIT + i + 100 * j; // 用 tag 區分兩組
// 每放一個 label,就把 contentSize 累加一個 label 寬
self.contentSize = CGSizeMake(self.contentSize.width + labelW, self.bounds.size.height);
[self addSubview:labelBackGroundView];
[self addSubview:textLabel];
}
}
}
tag 加上 100 * j 是為了讓兩組內容的 tag 不重複,後續若要依 tag 取 label 才不會抓錯。
一、必須加入 CommonModes。如果用預設的 defaultModes,滾動會明顯卡頓。原因是滑鼠/滑動事件與 timer 若處在同一個 runLoop mode,系統會優先回應滑動,timer 就被餓死。改用 NSRunLoopCommonModes 可以讓 timer 在滑動追蹤模式下照樣觸發。
二、timer 其實可以「暫停」。
NSTimer 的公開方法中只有 fire(立即啟動)與 invalidate(徹底作廢,無法再啟用),並沒有 pause。但它有一個 @property (copy) NSDate *fireDate,我們可以借它做手腳:
// 立即啟動 [timer setFireDate:[NSDate date]]; // 暫停(把下次觸發時間推到遙遠的未來) [timer setFireDate:[NSDate distantFuture]];
把觸發時間設成 distantFuture,timer 實際上就不會再跑,但物件依然存在;要恢復時把 fireDate 設回現在即可。這個小技巧比 invalidate 再重建要乾淨得多。
// 建立自動滾動 timer
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:SCROLL_TIME_INTERVAL
target:self
selector:@selector(autoScroll)
userInfo:nil
repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
[timer setFireDate:[NSDate date]];
self.timer = timer;
如果要做到「完全不掉幀」的連續滾動,timer 的呼叫頻率得非常高(一秒十次以上)。這時候回頭看 CPU 使用率,瞬間就衝高兩成左右。雖然還在可接受範圍,但為了這麼小的一個效果如此耗 CPU,顯然不划算。
解法:把位移交給動畫。UIView animateWithDuration 就能輕鬆勝任,Core Animation 會在背景執行緒算好每一幀,過渡順滑,CPU 也瞬間安靜下來。
副作用:用動畫過渡唯一的問題是,當控制器跳轉後再回來,動畫會直接跳到尾幀。細心的使用者可能會覺得突兀,這就在效能與效果之間取一個折衷點。
// 滾動間隔 #define SCROLL_TIME_INTERVAL 3 // 每次滾動距離 #define SCROLL_DISTANCE 100
// 自動滾動
- (void)autoScroll {
CGFloat offSet = SCROLL_DISTANCE;
// 若已滾進複製的那一半,就把偏移歸零,回到開頭,形成無限循環
if (self.contentOffset.x >= self.contentSize.width / 2) {
self.contentOffset = CGPointMake(0, 0);
}
// 用動畫承接這一次的位移
[UIView animateWithDuration:SCROLL_TIME_INTERVAL
delay:0
options:UIViewAnimationOptionCurveLinear
animations:^{
self.contentOffset = CGPointMake(self.contentOffset.x + offSet, self.contentOffset.y);
} completion:nil];
}
UIViewAnimationOptionCurveLinear 一定要加。預設的 ease-in-ease-out 會讓每一段位移都出現加速減速,字幕看起來像在抽搐;linear 才是跑馬燈該有的等速感。
跑馬燈的技術門檻不高,真正的價值在於三個細節:內容複製一份以實現無縫循環、timer 加入 CommonModes 避免卡頓、以及用動畫替代高頻 timer 來壓 CPU。這三點做到了,效果與效能就能同時拿到。