最近做项目,需求中要求用户名或密码输错时,输入框要抖动(类似Mac登录密码错误的抖动效果)。现将代码分享出来:
@interface UITextField (YHShakeUITextField)
- (void) shake;
@end
#import "YH-TextField.h"
#import <QuartzCore/QuartzCore.h>
@implementation UITextField (YHShakeUITextField)
//self.superView
- (void) shake {
CAKeyframeAnimation *keyAn = [CAKeyframeAnimation animationWithKeyPath:@"position"];
[keyAn setDuration:0.5f];
NSArray *array = [[NSArray alloc] initWithObjects:
[NSValue valueWithCGPoint:CGPointMake(self.center.x, self.center.y)],
[NSValue valueWithCGPoint:CGPointMake(self.center.x-5, self.center.y)],
[NSValue valueWithCGPoint:CGPointMake(self.center.x+5, self.center.y)],
[NSValue valueWithCGPoint:CGPointMake(self.center.x, self.center.y)],
[NSValue valueWithCGPoint:CGPointMake(self.center.x-5, self.center.y)],
[NSValue valueWithCGPoint:CGPointMake(self.center.x+5, self.center.y)],
[NSValue valueWithCGPoint:CGPointMake(self.center.x, self.center.y)],
[NSValue valueWithCGPoint:CGPointMake(self.center.x-5, self.center.y)],
[NSValue valueWithCGPoint:CGPointMake(self.center.x+5, self.center.y)],
[NSValue valueWithCGPoint:CGPointMake(self.center.x, self.center.y)],
nil];
[keyAn setValues:array];
[array release];
NSArray *times = [[NSArray alloc] initWithObjects:
[NSNumber numberWithFloat:0.1f],
[NSNumber numberWithFloat:0.2f],
[NSNumber numberWithFloat:0.3f],
[NSNumber numberWithFloat:0.4f],
[NSNumber numberWithFloat:0.5f],
[NSNumber numberWithFloat:0.6f],
[NSNumber numberWithFloat:0.7f],
[NSNumber numberWithFloat:0.8f],
[NSNumber numberWithFloat:0.9f],
[NSNumber numberWithFloat:1.0f],
nil];
[keyAn setKeyTimes:times];
[times release];
[self.layer addAnimation:keyAn forKey:@"TextAnim"];
}
@end
在登录的类里调用如下:
-(void)isloginbuttonClick
{
if ([userTextField.text length] == 0)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"watch out"
message:@"please input user"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil,nil];
[alertView show];
[alertView release];
[userTextField shake];
}
else if ([passwordTextField.text length] == 0)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"watch out"
message:@"please input password"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil, nil];
[alertView show];
[alertView release];
[passwordTextField shake];
}
else
{
SecondViewController *secondViewController = [[SecondViewController alloc] init];
[self.navigationController pushViewController:secondViewController animated:YES];
}
}