很久没有写博客了,最近看到一个软件中UITextField可以震动,感觉以后能用得上,所以想先把它记录下来,
主要用途:需要保存UITextField的内容,当输入框的输入不正确或者为空时,可以做清空输入框的内容,顺便带个震动的效果,这样就有点感觉,
步骤:
1.在ViewController中创建一个按钮和一个UITextField
2.在按钮上添加一个触发方法,在触发方法里面实现震动效果
源码:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.btn=[[UIButton alloc]initWithFrame:CGRectMake(30, 60, 260, 40)];
[self.btn setTitle:@"点击" forState:UIControlStateNormal];
[self.btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
[self.btn setBackgroundColor:[UIColor redColor]];
[self.view addSubview:self.btn];
self.text=[[UITextField alloc]initWithFrame:CGRectMake(30, 120, 260, 40)];
self.text.placeholder=@"请输入名称";
[self.view addSubview:self.text];
}
-(void)btnClick:(UIButton *)sender
{
CGRect frame = self.text.frame;
CAKeyframeAnimation *shakeAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
CGMutablePathRef shakePath = CGPathCreateMutable();
CGPathMoveToPoint(shakePath, NULL, frame.origin.x+frame.size.width/2, frame.origin.y+frame.size.height/2);
int index;
for (index = 3; index >=0; --index) {
CGPathAddLineToPoint(shakePath, NULL, frame.origin.x+frame.size.width/2 - frame.size.width * 0.02f * index, frame.origin.y+frame.size.height/2);
CGPathAddLineToPoint(shakePath, NULL, frame.origin.x+frame.size.width/2 + frame.size.width * 0.02f * index, frame.origin.y+frame.size.height/2);
}
CGPathCloseSubpath(shakePath);
shakeAnimation.path = shakePath;
shakeAnimation.duration = 0.5f;
shakeAnimation.removedOnCompletion = YES;
[self.text.layer addAnimation:shakeAnimation forKey:nil];
CFRelease(shakePath);
}
就这么简单的效果做出来了,是不是很容易,