1 - (float)randomFloatBetween:(float)min and:(float)max {
2 float diff = max - min;
3 return (((float) (arc4random() % ((unsigned)RAND_MAX + 1)) / RAND_MAX) * diff) + min;
4 }
5
6 -(void)showFlakes:(BOOL)need{
7 for (UIImageView *flake in self.snowFlakes) {
8 flake.hidden = !need;
9 }
10 }
11
12 -(void)singleFlakeSnow:(int)index{
13 UIView *flake = self.snowFlakes[index];
14 NSLayoutConstraint *x = self.flakesHorizonalPosition[index];
15 NSLayoutConstraint *y = self.flakesVerticalPosition[index];
16 int size = [self randomFloatBetween:8.0 and:14.0];
17 ((NSLayoutConstraint*)self.flakesWidth[index]).cOnstant= size;
18 ((NSLayoutConstraint*)self.flakesHeight[index]).cOnstant= size;
19 [flake.layer removeAllAnimations];
20 flake.layer.opacity = 0.1;
21 x.cOnstant= arc4random_uniform(CTScreenWidth);
22 y.cOnstant= -size;
23 float delay = arc4random_uniform(5.0);
24 [self layoutIfNeeded];
25 [UIView animateWithDuration:7.0 delay:delay options:UIViewAnimationOptionCurveEaseInOut animations:^{
26 x.cOnstant= x.constant + 40 - arc4random_uniform(80);
27 y.cOnstant= self.bounds.size.height;
28 flake.layer.opacity = 1.0;
29 [self layoutIfNeeded];
30 } completion:^(BOOL finished) {
31 if (finished) {
32 [[NSNotificationCenter defaultCenter] postNotificationName:REPEATSNOW object:nil userInfo:@{@"index":[NSNumber numberWithInt:index]}];
33 }
34 }];
35 }
36
37 -(void)snowAnimation:(BOOL)need{
38 if (need ) {
39 dispatch_async(dispatch_get_main_queue(), ^{
40 [self showFlakes:YES];
41 self.snowGround.hidden = FALSE;
42 self.snowBackground.hidden = FALSE;
43 [[NSNotificationCenter defaultCenter] removeObserver:self name:REPEATSNOW object:nil];
44 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveRepeatNotification:) name:REPEATSNOW object:nil];
45 for (UIView *flake in self.snowFlakes) {
46 [flake.layer removeAllAnimations];
47 }
48 for (int i = 0; i <[self.snowFlakes count]; i++) {
49 [self singleFlakeSnow:i];
50 }
51 });
52 }
53 else{
54 dispatch_async(dispatch_get_main_queue(), ^{
55 [[NSNotificationCenter defaultCenter] removeObserver:self name:REPEATSNOW object:nil];
56 for (UIView *flake in self.snowFlakes) {
57 [flake.layer removeAllAnimations];
58 }
59 [self showFlakes:NO];
60 });
61 }
62 }
63
64 -(void)receiveRepeatNotification:(NSNotification *)notification{
65 if ([[notification name] isEqualToString:REPEATSNOW]) {
66 int index = [((NSNumber*)[notification.userInfo objectForKey:@"index"]) intValue];
67 [self singleFlakeSnow:index];
68 }
69 }