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(阻尼系数)
范围 0~1 当它设置为1时,动画是平滑的没有振动的达到静止状态,越接近0 振动越大
velocity (弹性速率)
就是形变的速度,从视觉上看可以理解弹簧的形变速度,到动画结束,该速度减为0,所以,velocity速度越大,那么形变会越快,当然在同等时间内,速度的变化(就是速率)也会越快,因为速度最后都要到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) {
}];
}
}