Note that there are some explanatory texts on larger screens.

plurals
  1. POiPhone/Cocoa Animation having effect I don't understand
    text
    copied!<p>I have created a basic unlock slider like you use to unlock the iPhone.</p> <p>In my touchesEnded function, I use an animation to move the slider back to home.</p> <p>The first time the user moves the slider (and doesn't actually hit the end to unlock), the animation works fine and the slider moves back to home.</p> <p>However, the next time the user tries to move the slider (and touchesMoved gets called), the slider gets pushed offscreen (to the left) by the amount they had slid the slider before. </p> <p>So, what's happening?</p> <pre><code>- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { self.dragging = NO; self.startX = 0; [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:0.5]; self.unlock.frame = CGRectMake(0, 0, 75, 35); [UIView commitAnimations]; } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { if (!self.dragging ) { return; } UITouch *touch = [[event allTouches] anyObject]; CGPoint point = [touch locationInView:self]; int offset = point.x - self.startX; NSLog(@"%i", offset); if (offset &gt; (LENGTH-SIZE)) { offset = (LENGTH-SIZE); } CGAffineTransform myTransform = CGAffineTransformMakeTranslation(offset, 0.0); [self.unlock setTransform:myTransform]; if (point.x &gt;= (LENGTH-(SIZE-self.startX))) { NSLog(@"Slider reached end"); [self.sliderView removeFromSuperview]; } } </code></pre> <p>EDIT</p> <p>Here's the working function, cleaned up a bit, though it could be better (thanks to a couple answered questions on SO from one hacker). I'm going to blog the complete module since there doesn't seem to be a standard widget:</p> <pre><code>- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { if (!self.dragging ) { return; } UITouch *touch = [[event allTouches] anyObject]; CGPoint point = [touch locationInView:self]; if (point.x &gt;= (LENGTH-(SIZE-self.startX))) { NSLog(@"Slider reached end"); [self.sliderView removeFromSuperview]; } // offset based on where the user clicked the slider int offset = point.x - self.startX; if (offset &gt; (LENGTH-SIZE)) { offset = (LENGTH-SIZE); } //move the slider CGRect oldFrame = self.unlock.frame; CGRect newFrame = CGRectMake(self.frame.origin.x+offset, self.frame.origin.y-5, oldFrame.size.width, oldFrame.size.height); self.unlock.frame = newFrame; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload