为什么UIView动画不起作用

时间:2012-08-30 22:25:56

标签: objective-c

我要做的是以编程方式在屏幕的左上角创建一个UIView矩形,然后将其移动到右上角,右下角,左下角,最后再回到左上角。但它没有按预期工作。我的代码出了什么问题?

#import "ViewController.h"

@interface ViewController ()
@property (nonatomic,strong) UIView *myView;
@end

@implementation ViewController
@synthesize myView = _myView;


- (IBAction)animation:(UIButton *)sender {
    [UIView animateWithDuration:3.0 animations:^{
        self.myView.alpha = 0.75;
        self.myView.frame = CGRectMake(160, 0, 160,230);}];

    [UIView animateWithDuration:3.0 animations:^{
        self.myView.alpha = 0.50;
        self.myView.frame = CGRectMake(160, 230, 160,230);}];

     [UIView animateWithDuration:3.0 animations:^{
     self.myView.alpha = 0.25;
     self.myView.frame = CGRectMake(0, 230, 160,230);}];

     [UIView animateWithDuration:3.0 animations:^{
     self.myView.alpha = 0.00;
     self.myView.frame = CGRectMake(0, 0, 160,230);}
     completion:^(BOOL finished) {
     [self.myView removeFromSuperview];
     }];

}


- (void)viewDidLoad
{
    [super viewDidLoad];
    CGRect viewRect = CGRectMake(0, 0, 160, 230);
    UIView *mv = [[UIView alloc] initWithFrame:viewRect];
    self.myView = mv;
    self.myView.backgroundColor = [UIColor redColor];
    [self.view addSubview:self.myView];

}
@end

修改: 我用嵌套的完成块解决了这个问题:

- (IBAction)animation:(UIButton *)sender {
    [UIView animateWithDuration:3.0 animations:^{
        self.myView.alpha = 0.75;
        self.myView.frame = CGRectMake(160, 0, 160,230);}
     completion:^(BOOL finished) {
         [UIView animateWithDuration:3.0 animations:^{
             self.myView.alpha = 0.50;
             self.myView.frame = CGRectMake(160, 230, 160,230);}
          completion:^(BOOL finished) {
              [UIView animateWithDuration:3.0 animations:^{
                  self.myView.alpha = 0.25;
                  self.myView.frame = CGRectMake(0, 230, 160,230);}
          completion:^(BOOL finished) {
              [UIView animateWithDuration:3.0 animations:^{
                  self.myView.alpha = 0.00;
                  self.myView.frame = CGRectMake(0, 0, 160,230);}
                               completion:^(BOOL finished) {
                                   [self.myView removeFromSuperview];
          }];}];}];}];}

但阅读起来很糟糕。还有其他办法吗?

1 个答案:

答案 0 :(得分:0)

这不是特定的动画,但是您应该尝试使用此模式使动画的部件按顺序相继启动:

[UIView animateWithDuration:3.0 animations:^{
    // first part of the animation
} completion:^(BOOL finished) {
    [UIView animateWithDuration:3.0 animations:^{
        // second part of animation
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:3.0 animations:^{
            // third part of the animation
        } completion:^(BOOL finished) {
            [UIView animateWithDuration:3.0 animations:^{
                // forth part of the animation
            } completion:^(BOOL finished) {
                // finish and clear the animation
            }];
        }];
    }];
}];