Main Content

A single action for multiple iPad / iPhone buttons, and animation

Archive - Originally posted on "The Horse's Mouth" - 2012-03-11 21:25:48 - Graham Ellis

How do we add animation to an iPad / iPhone app? How do we share one action routine across a whole lot of similar buttons? These are amongst the questions that we looked at, and answered, in the little demonstration below during today's iOS / iPad / iPhone "Geekfest" ;-).


Here is the header file ViewController.h:

  #import
 
  @interface ViewController : UIViewController{
    UIButton *goUp;
    UIButton *goDown;
    UIImageView *crewe;
  }
 
  @property(nonatomic, retain) IBOutlet UIButton *goUp;
  @property(nonatomic, retain) IBOutlet UIButton *goDown;
  @property(nonatomic, retain) IBOutlet UIImageView *crewe;
 
  -(IBAction)movingImage:(id)sender;
@end


And the changes to ViewController.m:

  @synthesize goUp;
  @synthesize goDown;
  @synthesize crewe;


With the added action routine:

  -(IBAction)movingImage:(id)sender {
   
    if (sender == goUp) {
   
    [UIView beginAnimations:@"moveitup" context:NULL];
    [crewe setFrame:CGRectOffset([crewe frame],0,-400)];
    [UIView commitAnimations];
   
    } else {
 
    [UIView beginAnimations:@"moveitdown" context:NULL];
    [UIView setAnimationDuration:5.0];
     // Should really have used animateWithDuration
    [crewe setFrame:CGRectOffset([crewe frame],0,400)];
    [UIView commitAnimations];
   
    }
  }


Results: