iPhone Shake animation for Coin(Toss) flip and UILabel



In .h file


{
     NSArray* flipImages;
    

    int randomImgNum;

}

@property (strong, nonatomic) IBOutlet UIImageView *coin_view;

@property (weak, nonatomic) IBOutlet UILabel *coin_lbl;

In .m file


- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    if (motion == UIEventSubtypeMotionShake)
    {
        [self showAlert];
    }
}

-(IBAction)showAlert
{
    coin_lbl.hidden=YES;

    //get random number
   randomImgNum = arc4random_uniform(2);
    
    CATransition* transition = [CATransition animation];
    transition.startProgress = 0;
    transition.endProgress = 1.0;
    transition.type = @"flip";
    transition.subtype = @"fromRight";
    transition.duration = 0.2;
    transition.repeatCount=2;
    [coin_view.layer addAnimation:transition forKey:@"transition"];
    
    flipImages = [NSArray arrayWithObjects:[UIImage imageNamed:@"heads.png"],[UIImage imageNamed:@"tails.png"],nil];

    //use your random number to get an image from your array
    UIImage *tempImg = [flipImages objectAtIndex:randomImgNum];
    coin_view.image=tempImg;
    [self.view addSubview:coin_view];
    
    [NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(targetMethod)
        userInfo:nil repeats:NO];
}
-(void)targetMethod
{
    coin_lbl.hidden=NO;
    
    if (randomImgNum == 1)
    {
        coin_lbl.text=@"Tails";
           }
    else
    {
        coin_lbl.text=@"Heads";
    }
    
    [self shakeAnimation:coin_lbl];
    
}
-(void)shakeAnimation:(UILabel*) label
{
    CABasicAnimation *shake = [CABasicAnimation animationWithKeyPath:@"position"];
    [shake setDuration:0.1];
    [shake setRepeatCount:1];
    [shake setAutoreverses:YES];
    [shake setFromValue:[NSValue valueWithCGPoint:
                         CGPointMake(label.center.x - 5,label.center.y)]];
    [shake setToValue:[NSValue valueWithCGPoint:
                       CGPointMake(label.center.x + 5, label.center.y)]];
    [label.layer addAnimation:shake forKey:@"position"];
}

Comments

Popular posts from this blog

Parse JSON from a file and showing data into UITableView

Parse JSON from a URL and showing data into UITableView

iOS UIScrollView in UIView