Abdul Ahmad
Abdul Ahmad

Reputation: 10021

iOS dynamic object creation and storage

What I have is a UIButton. What I want to do is, every time the button is clicked, a new UIImageView is created (I will set the size/image etc... in a method) and the UIImageView falls to the bottom of the screen. How do I do this? I've tried creating the object and storing it in an NSMutableArray and doing a for loop on the array but that doesn't seem to work. (example of what I'm doing)

-(IBAction) button {
   [self createUiImage];
}
-(void) createUiImage {
   UIIMageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(50, 50, 15, 3)]
   iv.image = [UIImage imageNamed:@"image.png"];
   iv.hidden = NO;
   [self.view addSubview:iv];
   [array1 addObject:iv];
}
-(void) dropImageDown {
    for (UIImageView *a in array1) {
        a.center = CGPointMake(a.center.x, a.center.y + 10);
        if (a.center.y > 500) {
            [array1 removeAllObjects];
            [a removeFromSuperview];
        }
    }
}

and this dropImageDown method is being controlled by an NSTimer.

forgot to add this: The problem is that the shape isn't falling to the bottom, it appears and doesn't move!

I've also tried a for (int i = 0; i < array size; i ++) but thats not working either Appreciate the help, thanks

Upvotes: 0

Views: 112

Answers (3)

Abdul Ahmad
Abdul Ahmad

Reputation: 10021

Found the reason I was having issues... I was not initializing the NSMutableArray therefore it wasn't being recognized.

Upvotes: 0

Duncan C
Duncan C

Reputation: 131491

Don't try to use a timer and move the view in steps yourself. It will give jerky animation that puts a large burden on the CPU.

Use UIView animation instead.

Something like this:

-(void) animateImagesDown {
    for (UIImageView *a in array1) 
    {
      [UIView animateWithDuration: 1.0
      animations: ^
      {
        a.center = CGPointMake(a.center.x, 500);
      }
      completion: ^(BOOL finished) 
      {
        [a removeFromSuperview];
      }
      ];
    }
}

That code would animate all the view to a center position of 500, then remove them. (They would all be animated at the same time.)

UIView animations use ease-in, ease-out animation by default. There are other variations on the animateWithDuration UIView animation methods that let you control the animation timing. (look at the docs on the methodanimateWithDuration:delay:options:animations:completion:(Specifically the options parameter.)

Upvotes: 1

Related Questions