views:

295

answers:

1

I have implemented a slider bar type UI control, like the Unlock mechanism on the iPhone.

When the touchesEnded method gets called, I return the slider to it's starting position. Instead, I would like to animate its move back to it's starting position.

The code should be something like this, but it doesn't work. What am I doing wrong here?

Self.unlock is a UIImageView:

CABasicAnimation *theAnimation;
theAnimation = [CABasicAnimation animationWithKeyPath:@"position.x"];
theAnimation.fromValue = [NSNumber numberWithFloat:BEGINX];
theAnimation.toValue = [NSNumber numberWithFloat: 0.0];
theAnimation.duration = 0.5;
[self.unlock addAnimation: theAnimation];

Sorry for the bone-headed question!

+2  A: 

You can probably do this in a much simpler way using implicit animation. Assuming you currently are doing something like this:

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
  ...
  myView.frame = startingFrame;
  ...
}

You can use the implicit animator to animate any changes you make to the view (such as its frame):

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
  ...
  [UIView beginAnimations:nil context:nil];
  [UIView setAnimationDuration:0.5];
  myView.frame = startingFrame;
  [UIView commitAnimations];
  ...
}
Louis Gerbarg
Hey, thanks... I think I'm doing it wrong though. I tried the following code and I got a "UIImageView may not respond to" warning a couple of times: [self.unlock beginAnimations:nil context:nil]; [self.unlock setAnimationDuration:0.5]; self.unlock.frame = CGRectMake(0, 0, 75, 37); [self.unlock commitAnimations];
Andrew Johnson
Nevermind, I see your code is exactly correct as written. Works like a charm. Thanks!
Andrew Johnson