導航列標題、優惠訊息列、歌曲名稱……這些地方經常塞不下一整句話。與其讓系統呆呆地加上省略號,不如讓文字像跑馬燈一樣捲動,把內容完整交代出來。
概念是:先量出文字的實際寬度,若超出可視範圍,就用位移 transform 搭配線性、無限重複的動畫把它推過去。
#pragma mark - 動畫
- (void)startAnimationIfNeeded
{
// 先清掉舊動畫,避免連續呼叫時動畫疊加
[titleLabel.layer removeAllAnimations];
CGSize size = CGSizeMake(320, 2000); // 高度上限,用來量文字
NSDictionary *attribute = @{NSFontAttributeName: titleLabel.font};
CGSize textSize = [titleLabel.text boundingRectWithSize:size
options:NSStringDrawingTruncatesLastVisibleLine
attributes:attribute
context:nil].size;
CGRect lframe = titleLabel.frame;
lframe.size.width = textSize.width;
titleLabel.frame = lframe;
const float oriWidth = 10; // 可視寬度,實務上換成實際顯示區域
if (textSize.width > oriWidth) {
float offset = textSize.width - oriWidth;
[UIView animateWithDuration:18.0
delay:0
options:UIViewAnimationOptionRepeat // 動畫重複總開關
| UIViewAnimationOptionCurveLinear // 等速捲動,比較像跑馬燈
animations:^{
titleLabel.transform = CGAffineTransformMakeTranslation(-offset - 400, 0);
} completion:^(BOOL finished) {
}];
}
}
速度藏在 animateWithDuration 的第一個參數裡,跑動距離則由 offset 決定,兩者都能依版面自行調整。若想讓文字往返而不是單向捲出,可以再加上 UIViewAnimationOptionAutoreverse,但要注意它必須與 Repeat 一起使用才有效。
做跑馬燈之前,通常還得先處理好文字本身的排版。以下屬性幾乎每個專案都會用到:
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50, 20, 200, 50)];
label.text = @"label--label--label--label--";
label.font = [UIFont boldSystemFontOfSize:20]; // 系統字型則用 systemFontOfSize:
label.textColor = [UIColor orangeColor];
label.textAlignment = NSTextAlignmentRight; // 靠右/置中/靠左
label.adjustsFontSizeToFitWidth = YES; // 字級自動縮放以符合寬度
label.numberOfLines = 0; // 0 代表不限制行數
label.lineBreakMode = NSLineBreakByTruncatingMiddle; // 過長時截去中間
label.highlighted = YES;
label.highlightedTextColor = [UIColor orangeColor];
label.shadowColor = [UIColor redColor];
label.shadowOffset = CGSizeMake(1.0, 1.0);
label.backgroundColor = [UIColor clearColor];
label.userInteractionEnabled = YES;
label.enabled = NO; // 文字變灰、不可編輯
[self.view addSubview:label];
lineBreakMode 共有六種:尾端截斷、頭部截斷、中間截斷、直接裁切、單字換行與依字元換行。搭配 numberOfLines 使用時,多行情境建議選 NSLineBreakByCharWrapping,中文才不會出現奇怪的斷行。另外,當 adjustsFontSizeToFitWidth 為 YES 時,baselineAdjustment 會決定文字基線的對齊方式,通常保持預設即可。