iOS 7 之后新出來一個阻尼動畫璧尸,類似于彈簧效果的API:
+ (void)animateWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay usingSpringWithDamping:(CGFloat)dampingRatio initialSpringVelocity:(CGFloat)velocity options:(UIViewAnimationOptions)options animations:(void (^)(void))animations completion:(void (^ __nullable)(BOOL finished))completion NS_AVAILABLE_IOS(7_0);
dampingRatio(阻尼系數(shù))
范圍 0~1 當它設(shè)置為1時供常,動畫是平滑的沒有振動的達到靜止狀態(tài)骇两,越接近0 振動越大
velocity (彈性速率)
就是形變的速度,從視覺上看可以理解彈簧的形變速度呻右,到動畫結(jié)束,該速度減為0,所以茂装,velocity速度越大怠蹂,那么形變會越快善延,當然在同等時間內(nèi),速度的變化(就是速率)也會越快城侧,因為速度最后都要到0易遣。
效果:
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *button =[UIButton buttonWithType:UIButtonTypeCustom];
button.backgroundColor =[UIColor greenColor];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[button setTitle:@"展開" forState:UIControlStateNormal];
[button setTitle:@"收起" forState:UIControlStateSelected];
button.frame = CGRectMake(Device_Width - 100, 200, 80, 40);
[button addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
_label =[[UILabel alloc]initWithFrame:CGRectMake(Device_Width - 100, 200, 0, 40)];
_label.backgroundColor =[UIColor cyanColor];
_label.text = @"哈哈哈";
[self.view addSubview:_label];
}
-(void)btnClick:(UIButton *)button
{
button.selected = !button.selected;
if (button.selected) {
[UIView animateWithDuration:1 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:0.6 options:UIViewAnimationOptionCurveLinear animations:^{
_label.frame = CGRectMake(Device_Width - 300, 200, 100, 40 );
} completion:^(BOOL finished) {
}];
}
if (!button.selected) {
[UIView animateWithDuration:0.3 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:0.6 options:UIViewAnimationOptionCurveLinear animations:^{
_label.frame = CGRectMake(Device_Width - 100, 200, 0, 40 );
} completion:^(BOOL finished) {
}];
}
}