1、添加定时器以及图片
@interface ViewController ()
/** 定时器 */
@property (strong, nonatomic) CADisplayLink *displayLink;
/** 图片 */
@property (strong, nonatomic) UIImage *image;
@end
2、初始化定时器以及图片
- (void)viewDidLoad {
[super viewDidLoad];
self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(handlerAction:)];
self.displayLink.frameInterval = 60;
self.image = [UIImage imageNamed:@"icon_hongbao"];
[self startFlyWithEmojiImage:self.image onView:self.view];
}
- (void)startFlyWithEmojiImage:(UIImage *)image onView:(UIView *)view{
self.image = image;
[self.displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
}
3、添加红包button,添加动画
- (void)handlerAction:(CADisplayLink *)displayLink{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:self.image forState:UIControlStateNormal];
button.frame = CGRectMake(0, 0, 50, 60);
button.bounds = CGRectMake(0, 0, 50, 60);
button.enabled = YES;
button.userInteractionEnabled = NO;
[button addTarget:self action:@selector(doTap:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
CGSize viewSize = self.view.bounds.size;
CGFloat x = arc4random_uniform(viewSize.width);
CGFloat y = -button.frame.size.height;
button.center = CGPointMake(x, y);
[UIView animateWithDuration:30 animations:^{
CGFloat toX = arc4random_uniform(viewSize.width);
CGFloat toY = viewSize.height + button.frame.size.height * 0.5;
button.center = CGPointMake(toX, toY);
} completion:^(BOOL finished) {
[button removeFromSuperview];
}];
}
4、在移动中的 view需要通过hitTest来判断点击位置
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *t = [touches anyObject];
CGPoint location = [t locationInView:self.view];
for (UIButton *button in self.view.subviews)
{
if ([button.layer.presentationLayer hitTest:location])
{
[button removeFromSuperview];
break;
}
}
}