如何在动画到达屏幕上的某个点时发出警报。目标C.

时间:2013-03-30 17:07:32

标签: objective-c xcode cocoa-touch

我有一个动画,它不断在屏幕上运行。现在,当你在屏幕的某个部分触摸动画时,我正试图发出警报。

目前我已经到了这样的程度:如果你触摸屏幕中间,你会收到警报。

SelectedCellViewController.h

#import <Accounts/Accounts.h>
#import <QuartzCore/QuartzCore.h>

@interface SelectedCellViewController : UIViewController {
IBOutlet UIImageView *rocket;
}

@end

SelectedCellViewController.m

#import "SelectedCellViewController.h"

@interface SelectedCellViewController ()

@end

@implementation SelectedCellViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
}
return self;
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}

#pragma mark - View lifecycle

- (void)viewDidLoad {

[super viewDidLoad];

[self performSelector:@selector(imageSpawn:) withObject:nil afterDelay:3];

  }


     - (void) imageSpawn:(id) sender
   {

      UIImage* image = [UIImage imageNamed:@"ae"];
      rocket = [[UIImageView alloc] initWithImage:image];
       rocket.frame = CGRectMake(-25, 200, 25, 40);
       [UIView animateWithDuration:5
                      delay:0.2f
                    options:UIViewAnimationCurveEaseInOut | UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse
                 animations:^(){rocket.frame=CGRectMake(345, 200, 25, 40);}
                 completion:^(BOOL fin) {
                 }];

   UITapGestureRecognizer *tapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(ballTapped:)];
tapped.numberOfTapsRequired = 1;
[self.view addGestureRecognizer:tapped];
[self.view setUserInteractionEnabled:YES];
[self.view addSubview:rocket];

}

-(void)ballTapped:(UIGestureRecognizer *)gesture
{

//  [rocket.layer removeAllAnimations];
NSLog(@"Tag = %d", gesture.view.tag);

 CGPoint location = [gesture locationInView:gesture.view];

rocket.frame = CGRectMake(location.x,location.y,25,40);

 CGPoint location1 = [gesture locationInView:gesture.view];
CGRect rectToCompare =  CGRectMake(10.0f, 200.0f, 200.0f, 42.0f);

if (CGRectContainsPoint(rectToCompare, location1)) {

    //trigger an event.
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Tapped row!"
                                                    message:[NSString stringWithFormat:@"Shot"]
                                                   delegate:nil
                                          cancelButtonTitle:@"Yes, I did!"
                                          otherButtonTitles:nil];
    [alert show];
}

}

- (void)viewDidUnload {

}

@end 

1 个答案:

答案 0 :(得分:1)

要在动画中间获取视图属性的值,您必须使用视图图层的presentationLayer。正如documentation states

  

此方法返回的图层对象提供了当前在屏幕上显示的图层的近似值。当动画正在进行时,您可以检索此对象并使用它来获取这些动画的当前值。

因此,您可以使用view.layer.presentationLayer.frame view作为您的UIImageView来获取动画图层在屏幕上的当前位置。使用它,测试帧是否在您想要检测的边界内是微不足道的。