温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-10-17 16:23:31 来源:脚本之家 阅读:232 作者:iOS_ziank 栏目:移动开发

前言

大家都知道在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];
}

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

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

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

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

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

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

总结

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI