這個效果很常見:底部一排分頁按鈕,點下去時下方那塊指示條會滑過去,帶一點回彈的彈性手感。用巢狀的 animateWithDuration:animations:completion: 就能做到,關鍵是 __block 修飾的 frame 變數可以在多層 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;
}];
}];
}];
}
三段位移的用意是:先衝過頭一點,再往反方向修正過多,最後微調回位。這種「過衝再收斂」的節奏,比單純 linear 位移更有彈性手感。
- (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];
UIView *bgLayer = [[UIView alloc] initWithFrame:blockBg.frame];
bgLayer.backgroundColor = [UIColor clearColor];
bgLayer.layer.opacity = 0.4f;
[blockBg addSubview:bgLayer];
self.block = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 64, 20)];
self.block.backgroundColor = [UIColor orangeColor];
self.block.layer.opacity = 1.0f;
[blockBg addSubview:self.block];
}
硬編碼的數字換成比例。 按鈕寬度 64、容器寬 320 是 iPhone 5 時代的數字。用 self.view.bounds.size.width / 按鈕數量 計算,並在旋轉或尺寸變更時重新布局,才能對齊各種螢幕。
duration 用 0.1 秒的三段串接,總長 0.3 秒。 想更省事,可以用 UIView 的 spring 動畫(animateWithDuration:delay:usingSpringWithDamping:initialSpringVelocity:options:completions:),一行就得到自然回彈,不必手動拆三段。
block 屬性用 weak 更安全。 這裡 self.block 是 subview,view 已經持有它了,property 再 retain 一次沒意義。ARC 下應寫成 @property (nonatomic, weak) UIView *block;,避免忘記在 dealloc 釋放。
completion 的 finished 參數別忽略。 若動畫中途被打斷(例如使用者連點),finished 會是 NO,此時繼續跑下一段動畫容易導致位置錯亂。實務上應在 if (finished) 內才接續,或改用一個「目標 index」搭配絕對位置計算,讓動畫隨時可以安全重入。