James Anderson
James Anderson

Reputation: 566

How can I allow touches on a UIButton whilst it is moving in an animation?

Here's my code:

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:100];
[UIView setAnimationRepeatCount:1000];
[UIView setAnimationRepeatAutoreverses:NO];
[UIView setAnimationBeginsFromCurrentState:YES];

CGFloat x = (CGFloat) (arc4random() % (int) self.view.bounds.size.width);
CGFloat y = (CGFloat) (arc4random() % (int) 463);

if(y < 90)
    y = 90;

if(x > 270)
    x = 270;

CGPoint squarePostion = CGPointMake(x, y);

button.center = squarePostion;

[UIView setAnimationDelegate:self];
[UIView commitAnimations];

I understand that I need to add 'UIViewAnimationOptionAllowUserInteraction' somewhere, but how can I do this?

Upvotes: 0

Views: 36

Answers (1)

Mohit
Mohit

Reputation: 3416

This worked for me during animation. hope will also work for you. Add button object to array during animation and remove from it when animation is completed.

[self.arrBtn addObject:btn];

[self.view addSubview:btn];
[self.view bringSubviewToFront:btn];

[UIView animateWithDuration:8.0f
                      delay:0.0f
                    options:UIViewAnimationOptionAllowUserInteraction
                 animations:^{
                     btn.frame = CGRectMake(endX, 500.0, 50.0 * scale, 50.0 * scale);
                 }
                 completion:^(BOOL finished){

                     [self.arrBtn removeObject:btn];

                 }]; 


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint touchLocation = [touch locationInView:self.view];
for (UIButton *button in self.arrBtn) // arrBtn is array of button
{
    if ([button.layer.presentationLayer hitTest:touchLocation])
    {
        // This button was hit whilst moving - do something with it here

        NSLog(@"Button Clicked");
        break;
    }
}
}

Upvotes: 1

Related Questions