What I am trying to do is to programmatically create a UIView rectangle in upper left corner of screen, then move it to upper right, lower right, lower left, finally back to upper left. But it doesn’t work as intended. What’s wrong with my code?
#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
EDIT:
I fix the problem with nested completion blocks:
- (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];
}];}];}];}];}
Yet it’s terrible to read. Is there any other way?
this is not the specific animation, but you should try this pattern to make the animations’ parts launch after each other sequentially: