這個範例示範如何製作一個「底部按鈕列 + 可滑動高亮塊」的導航元件。重點在於利用 block 的巢狀呼叫,把一段三段式的彈跳動畫串起來。
畫面上有五個並排的按鈕(主菜單、收藏、最近使用、更多…),按鈕下方有一層半透明的底軌,底軌上再放一個高亮的橘色方塊。點擊任一個按鈕時,橘色方塊會滑向該按鈕,並帶一點過衝後回彈的效果。
@property (nonatomic, retain) UIView *block; // 可滑動的高亮塊
- (void)btnClicked:(UIButton *)sender {
__block CGRect targetFrame = self.block.frame;
BOOL directionRight = targetFrame.origin.x < sender.frame.origin.x;
targetFrame.origin.x = sender.frame.origin.x + (directionRight ? 30 : -30);
[UIView animateWithDuration:0.1 animations:^{
self.block.frame = targetFrame;
} completion:^(BOOL finished){
targetFrame.origin.x += directionRight ? -50 : 50;
[UIView animateWithDuration:0.1 animations:^{
self.block.frame = targetFrame;
} completion:^(BOOL finished){
targetFrame.origin.x += directionRight ? 20 : -20;
[UIView animateWithDuration:0.1 animations:^{
self.block.frame = targetFrame;
}];
}];
}];
}
先判斷移動方向(右移或左移),然後把目標 x 座標先「衝過頭」30 點;接著回退 50 點;最後再補回 20 點。三段各 0.1 秒的動畫串接起來,就形成了「衝出 → 回彈 → 收斂」的彈性手感。
這裡有兩個 Objective-C 重點:__block 修飾符讓 targetFrame 在 block 內被修改後,外層與後續 block 都能看到最新值;而 block 的巢狀呼叫本質上是「動畫完成後的回呼」,因此三段動畫是嚴格依序執行的,不會互相搶。
- (void)buildLayout {
NSArray *arrBtn = @[@"主菜單", @"收藏", @"最近使用", @"更多"];
self.view.backgroundColor =
[UIColor colorWithRed:241/255.0f green:200/255.0f blue:55/255.0f alpha:1.0f];
for (int i = 0; i < 4; i++) {
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(64 * i, CGRectGetHeight(self.view.bounds) - 40, 64, 40);
[btn setTitle:[arrBtn objectAtIndex:i] forState:UIControlStateNormal];
btn.layer.backgroundColor = [UIColor clearColor].CGColor;
btn.layer.borderWidth = 1.0f;
[btn addTarget:self action:@selector(btnClicked:)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
UIView *blockBg = [[UIView alloc] initWithFrame:
CGRectMake(0, CGRectGetHeight(self.view.bounds) - 60, 320, 20)];
blockBg.backgroundColor = [UIColor clearColor];
[self.view addSubview:blockBg];
self.block = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 64, 20)];
self.block.backgroundColor = [UIColor orangeColor];
[blockBg addSubview:self.block];
}
1. 用 spring 動畫取代三段串接。 iOS 7 起就有 animateWithDuration:delay:usingSpringWithDamping:initialSpringVelocity:options:animations:,一行就能做出自然回彈,比手動拆三段簡潔許多:
[UIView animateWithDuration:0.4 delay:0
usingSpringWithDamping:0.6 initialSpringVelocity:0.8
options:0 animations:^{
self.block.frame = targetFrame;
} completion:nil];
2. 硬編碼的座標應該抽成常數。 範例中的 64、30、50、20 都是agic number,建議用版面寬度除以按鈕數自動計算,這樣才能適配不同螢幕尺寸。
3. 用 UISegmentedControl 或 UICollectionView 會更省事。 若只是要「選單 + 滑動指示器」,UICollectionView 搭配一個跟著 contentOffset 移動的 indicator view,天生就支援手勢拖動,不必自己寫點擊動畫。