iOS UIAlertController中UITextField添加晃動效果與邊框顏色詳解
前言
大家都知道在iOS8中引入了UIAlertController,通過UIAlertController可以方便的添加文本框進行編輯,但是,在輸入錯誤的內(nèi)容時,如何對用戶進行提醒就成了問題,因為UIAlertController中的所有UIAlertAction都會導(dǎo)致UIAlertController的消失。這里,我就描述兩種提示的方法,分別是晃動文本框和修改邊框的顏色。下面話不多說了,來一起看看詳細的實現(xiàn)方法吧。
晃動UITextField
晃動UITextField其實就是對它添加一個動畫效果,參考了Stack Overflow上的做法,通過添加position的動畫,可以實現(xiàn)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]; }
而在實際中我們應(yīng)該這樣修改:
- (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]; }]; }
這樣的產(chǎn)生效果才是我們想要的。
需要注意的是:一定要在present以后進行設(shè)置,否則會發(fā)現(xiàn)設(shè)置是無效的,因為沒有present之前,textField的superview是nil,設(shè)置是無效的。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,本文還有許多不足,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
iOS系統(tǒng)和微信中不支持audio自動播放問題的解決方法
最近在微信端開發(fā)H5的時候,audio標簽在蘋果機上無法進行自動播放,查找相關(guān)資料終于解決了,所以下面這篇文章主要給大家介紹了關(guān)于iOS系統(tǒng)和微信中不支持audio自動播放問題的解決方法,需要的朋友可以參考下。2017-09-09實例講解iOS應(yīng)用開發(fā)中UIPickerView滾動選擇欄的用法
這篇文章主要介紹了iOS應(yīng)用開發(fā)中UIPickerView滾動選擇欄的用法,示例代碼基于傳統(tǒng)的Objective-C,需要的朋友可以參考下2016-04-04iOS開發(fā)之1行代碼實現(xiàn)緩存計算及清除緩存
這篇文章主要給大家介紹了關(guān)于iOS開發(fā)之1行代碼實現(xiàn)緩存計算及清除緩存的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對各位iOS開發(fā)者們具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05