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

时间:2022-09-19 16:18:23

前言

大家都知道在ios8中引入了uialertcontroller,通过uialertcontroller可以方便的添加文本框进行编辑,但是,在输入错误的内容时,如何对用户进行提醒就成了问题,因为uialertcontroller中的所有uialertaction都会导致uialertcontroller的消失。这里,我就描述两种提示的方法,分别是晃动文本框和修改边框的颜色。下面话不多说了,来一起看看详细的实现方法吧。

晃动uitextfield

晃动uitextfield其实就是对它添加一个动画效果,参考了stack overflow上的做法,通过添加position的动画,可以实现uialertcontroller中的uitextfield的晃动效果。

?
1
2
3
4
5
6
7
8
9
- (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将会变成下图样式:

?
1
2
3
4
5
6
7
8
9
- (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添加晃动效果与边框颜色详解

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

?
1
2
3
4
5
6
7
8
9
10
- (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,设置是无效的。

总结

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

原文链接:http://www.jianshu.com/p/1b2941be32fa