iOS UIAlertController中UITextField添加晃动效果与边框颜色详解

时间:2019-04-07
本文章向大家介绍iOS UIAlertController中UITextField添加晃动效果与边框颜色详解,主要包括iOS 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中文本框的默认边框颜色都是黑色,通常在输入异常时会改为红色进行提醒,这个时候,如果直接修改UITextField的border将会变成下图样式:

- (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];
}


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

- (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];
 }];
}

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


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

总结

以上就是这篇文章的全部内容了,本文还有许多不足,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。