iosfacebook-pop

Can I apply the same animation to multiple text fields?


I'm creating a method that shakes my UITextField and use POP to do the heavy lifting.

- (void)textFieldErrorAnimation {

    POPSpringAnimation *shake = [POPSpringAnimation animationWithPropertyNamed:kPOPLayerPositionX];

    shake.springBounciness = 10;
    shake.velocity = @(2000);


    [self.value.layer pop_addAnimation:shake forKey:@"shakeValue"];
    [self.year.layer pop_addAnimation:shake forKey:@"shakeYear"];
}

It seems to be working when I apply the animation to the object "value" but not when it's applied to "value" and "year" at the same time.

I know I can create a shake2, shake3 etc so basically one for each textField but it seems strange that i'd need to do that.

Any ideas how I can reuse this animation?


Solution

  • Of course you can. What I really do about, this kind of reusing animations is creating a method that returns the animation and setting the name and key values correctly.

    - (POPSpringAnimation *)popShakeAnimation {
    
    
    POPSpringAnimation *shakeAnimation = [POPSpringAnimation animationWithPropertyNamed:kPOPLayerPositionX];
    shakeAnimation.velocity = @2000;
    shakeAnimation.springBounciness = 20;
    shakeAnimation.name = @"shakeAnimation";
    
    return shakeAnimation;
    

    }

    and then whenever I need to shake any views I simply add them to the views' layer.

        [self.textfield001.layer pop_addAnimation:[self popShakeAnimation]
                                                forKey:@"shakeAnimation"];
        [self.textfield002.layer pop_addAnimation:[self popShakeAnimation]
                                                forKey:@"shakeAnimation"];
        [self.textfield003.layer pop_addAnimation:[self popShakeAnimation]
                                                  forKey:@"shakeAnimation"];
    

    Just remember to set key values to the name you've created with the animation in the first place.