UIAlertController中的UITextField晃动效果和边框颜色

在iOS8中,我们引入了UIAlertController,通过UIAlertController可以方便的添加文本框进行编辑,但是,在输入错误的内容时,如何对用户进行提醒就成了问题,因为UIAlertController中的所有UIAlertAction都会导致UIAlertController的消失。这里,我就描述两种提示的方法,分别是晃动文本框和修改边框的颜色。

晃动UITextField

晃动UITextField其实就是对它添加一个动画效果,参考了Stack Overflow上的做法,通过添加position的动画,可以实现UIAlertController中的UITextField的晃动效果。

- (void)shakeField:(UITextField *)textField {
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    animation.duration = 0.07;
    animation.repeatCount = 4;
    animation.autoreverses = YES;
    animation.fromValue = [NSValue valueWithCGPoint:CGPointMake(textField.centerX - 10, textField.centerY)];
    animation.toValue = [NSValue valueWithCGPoint:CGPointMake(textField.centerX + 10, textField.centerY)];
    [textField.layer addAnimation:animation forKey:@"position"];
}

修改UITextField的边框颜色

UIAlertController中文本框的默认边框颜色都是黑色,通常在输入异常时会改为红色进行提醒,这个时候,如果直接修改UITextFieldborder将会变成下图样式:

- (void)testAlert {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"测试" message:@"测试输入框边框颜色" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.layer.borderColor = [UIColor redColor].CGColor;
        textField.layer.borderWidth = 1;
    }];
    [self presentViewController:alert animated:YES completion:nil];
}
Simulator Screen Shot 2016年12月27日 上午10.11.40.png

而在实际中我们应该这样修改:

- (void)testAlert {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"测试" message:@"测试输入框边框颜色" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        self.currentField = textField;
    }];
    [self presentViewController:alert animated:YES completion:^{
        [[self.currentField superview] superview].backgroundColor = [UIColor redColor];
    }];
}

这样的产生效果才是我们想要的。

Simulator Screen Shot 2016年12月27日 上午10.15.22.png

需要注意的是:一定要在present以后进行设置,否则会发现设置是无效的,因为没有present之前,textFieldsuperviewnil,设置是无效的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值