UITextField的震动效果

很久没有写博客了,最近看到一个软件中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);

}

就这么简单的效果做出来了,是不是很容易,

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值