在iOS8中,我們引入了UIAlertController
,通過(guò)UIAlertController
可以方便的添加文本框進(jìn)行編輯,但是,在輸入錯(cuò)誤的內(nèi)容時(shí),如何對(duì)用戶進(jìn)行提醒就成了問題,因?yàn)?code>UIAlertController中的所有UIAlertAction
都會(huì)導(dǎo)致UIAlertController
的消失。這里,我就描述兩種提示的方法,分別是晃動(dòng)文本框和修改邊框的顏色。
晃動(dòng)UITextField
晃動(dòng)UITextField
其實(shí)就是對(duì)它添加一個(gè)動(dòng)畫效果,參考了Stack Overflow上的做法,通過(guò)添加position
的動(dòng)畫,可以實(shí)現(xiàn)UIAlertController
中的UITextField
的晃動(dòng)效果。
- (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
中文本框的默認(rèn)邊框顏色都是黑色,通常在輸入異常時(shí)會(huì)改為紅色進(jìn)行提醒,這個(gè)時(shí)候,如果直接修改UITextField
的border
將會(huì)變成下圖樣式:
- (void)testAlert {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"測(cè)試" message:@"測(cè)試輸入框邊框顏色" 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
而在實(shí)際中我們應(yīng)該這樣修改:
- (void)testAlert {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"測(cè)試" message:@"測(cè)試輸入框邊框顏色" 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];
}];
}
這樣的產(chǎn)生效果才是我們想要的。
Simulator Screen Shot 2016年12月27日 上午10.15.22.png
需要注意的是:一定要在present
以后進(jìn)行設(shè)置,否則會(huì)發(fā)現(xiàn)設(shè)置是無(wú)效的,因?yàn)闆]有present
之前,textField
的superview
是nil
,設(shè)置是無(wú)效的。