免费开源的iOS开发学习平台

UIView详解:5-视图的动画

当修改UIView的某些外观属性的时候,iOS提供了动画播放的效果,能够通过动画的方式来展现出外观变化的过程,给用户提供了比较好的体验。

UIView类中支持动画的属性

动画为用户界面在不同外观状态之间的迁移过程提供了流畅的视觉效果,动画播放的功能也是苹果自家的看家本领。在UIView类中,支持动画的属性如下所示,即:在开发过程中,修改如下属性,可以考虑添加动画效果。

  • UIView中可以添加动画的属性
@property(nonatomic) CGRect            frame;
@property(nonatomic) CGRect            bounds;
@property(nonatomic) CGPoint           center; 
@property(nonatomic) CGAffineTransform transform;
@property(nullable, nonatomic,copy)            UIColor          *backgroundColor; 
@property(nonatomic)                 CGFloat           alpha;

常用动画播放的方法

当需要播放动画时,经常使用具有播放动画效果的方法。在如下的方法中,可以设置动画播放的时间,动画播放的内容以及动画播放完毕后的操作。动画也可以支持嵌套。

/*UIView有关动画的属性和方法*/
+ (void)animateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations completion:(void (^ __nullable)(BOOL finished))completion NS_AVAILABLE_IOS(4_0); 
+ (void)animateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations NS_AVAILABLE_IOS(4_0);

在下方的示例代码中,会在1秒内修改myView的背景颜色为红色,同时放大1.2倍,当动画播放完成后,再把myView的背景颜色改为绿色并恢复初始大小。

- (IBAction)playAnimation:(id)sender {
    [UIView animateWithDuration:1.0 animations:^{      
        self.myView.backgroundColor = [UIColor redColor];
        self.myView.transform = CGAffineTransformScale(self.myView.transform, 1.2,1.2);     
    } completion:^(BOOL finished) {        
        [UIView animateWithDuration:1.0 animations:^{
            self.myView.backgroundColor = [UIColor greenColor];
            self.myView.transform = CGAffineTransformIdentity;
        }];
    }];   
}

示例代码

https://github.com/99ios/7.2.5