0

我要做的是以编程方式在屏幕的左上角创建一个 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];
          }];}];}];}];}

然而读起来很可怕。还有其他方法吗?

4

1 回答 1

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
            }];
        }];
    }];
}];
于 2012-08-30T22:44:59.070 回答