想要讓畫面上的區塊有「上滑展開、下滑收起」的流暢效果嗎?透過 UIView 的 animateWithDuration: 系列方法,只要改變 center 座標,就能輕鬆做出平移動畫。以下我用一個簡單 Demo 記錄實作過程。
下圖為上下移動切換的效果:
我用一個 typeView 變數記錄目前狀態(上、中、下),再依狀態切換兩個 view 的 center 位置。上滑事件:
- (IBAction)upChange:(id)sender {
if (typeView == down) {
[self.downBtn setHidden:NO];
[self.upBtn setHidden:NO];
[UIView animateWithDuration:0.5 animations:^{
self.upView.center = CGPointMake(self.upView.center.x, 0);
self.downView.center = CGPointMake(self.downView.center.x,
(self.upView.frame.size.height + self.downView.frame.size.height) / 2);
}];
typeView = middle;
} else if (typeView == middle) {
[self.downBtn setHidden:NO];
[self.upBtn setHidden:YES];
[UIView animateWithDuration:0.5 animations:^{
self.upView.center = CGPointMake(self.upView.center.x, -(self.upView.frame.size.height / 2));
self.downView.center = CGPointMake(self.downView.center.x, self.downView.frame.size.height / 2);
}];
typeView = up;
}
}
下滑事件則是反向操作:
- (IBAction)downChange:(id)sender {
if (typeView == middle) {
[self.downBtn setHidden:YES];
[self.upBtn setHidden:NO];
[UIView animateWithDuration:0.5 animations:^{
self.upView.center = CGPointMake(self.upView.center.x, self.upView.frame.size.height / 2);
self.downView.center = CGPointMake(self.downView.center.x,
self.upView.frame.size.height + self.downView.frame.size.height / 2);
}];
typeView = down;
} else if (typeView == up) {
// 從 up 回到 middle 的過渡動畫
...
typeView = middle;
}
}
這裡有個小細節要注意:兩個 view 的大小必須精確計算,才能算出正確的目標座標,讓動畫收尾的位置剛剛好。
基本原型:
+ (void)animateWithDuration:(NSTimeInterval)duration
animations:(void (^)(void))animations;
// 預設 delay = 0.0, options = 0, completion = NULL
參數說明:duration 是動畫持續時間;animations 區塊中定義所有要做動畫的屬性。
另外還有兩個更完整的版本:
+ (void)animateWithDuration:(NSTimeInterval)duration
delay:(NSTimeInterval)delay
options:(UIViewAnimationOptions)options
animations:(void (^)(void))animations
completion:(void (^)(BOOL finished))completion;
+ (void)animateWithDuration:(NSTimeInterval)duration
animations:(void (^)(void))animations
completion:(void (^)(BOOL finished))completion;
// delay = 0.0, options = 0
其中 options 是動畫執行的選項(例如節奏曲線、是否重播),completion 則是動畫完成後要執行的區塊。靈活運用這些參數,就能做出更豐富的轉場效果。