iOS - UITextField
前言
NS_CLASS_AVAILABLE_IOS(2_0) @interface UITextField : UIControl <UITextInput, NSCoding>@available(iOS 2.0, *) public class UITextField : UIControl, UITextInput, NSCoding1、UITextField 的創建
Objective-C
// 實例化 UITextField 對象UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(20, 100, 200, 30)];// 將 textField 加到 window 上顯示出來[self.view addSubview:textField];Swift
// 實例化 UITextField 對象let textField:UITextField = UITextField(frame: CGRectMake(20, 100, 200, 30))// 將 textField 加到 window 上顯示出來 self.view.addSubview(textField)
2、UITextField 的設置
Objective-C
// 設置邊框樣式/*UITextBorderStyleNone, 無邊框,默認UITextBorderStyleLine, 直線邊框UITextBorderStyleBezel, 邊框 + 陰影UITextBorderStyleRoundedRect 圓角矩形邊框*/textField.borderStyle = UITextBorderStyleLine;// 設置背景顏色/*默認是透明的*/textField.backgroundColor = [UIColor yellowColor];// 設置背景圖片textField.background = [UIImage imageNamed:@"pic2"];// 設置提示文字/*用戶輸入時自動消失*/textField.placeholder = @"請輸入用戶名";// 設置輸入的字體顏色textField.textColor = [UIColor redColor];// 設置文字對齊方式textField.textAlignment = NSTextAlignmentLeft;// 設置最小可縮小的字號textField.minimumFontSize = 10;// 自動調整文字大小/*自動調整文字的大小以適應 textField 的寬度*/textField.adjustsFontSizeToFitWidth = YES;// 設置密文輸入模式/*default is NO*/textField.secureTextEntry = YES;// 設置顯示清除按鈕 /*UITextFieldViewModeNever, // defaultUITextFieldViewModeWhileEditing,UITextFieldViewModeUnlessEditing,UITextFieldViewModeAlways*/textField.clearButtonMode = UITextFieldViewModeWhileEditing;// 設置鍵盤樣式/*UIKeyboardTypeDefault, // Default type for the current input method.UIKeyboardTypeASCIICapable, // Displays a keyboard which can enter ASCII characters,// non-ASCII keyboards remain activeUIKeyboardTypeNumbersAndPunctuation, // Numbers and assorted punctuation.UIKeyboardTypeURL, // A type optimized for URL entry.UIKeyboardTypeNumberPad, // A number pad (0-9). Suitable for PIN entry.UIKeyboardTypePhonePad, // A phone pad (1-9, *, 0, #, with letters under the numbers).UIKeyboardTypeNamePhonePad, // A type optimized for entering a person's name or phone number.UIKeyboardTypeEmailAddress, // A type optimized for multiple email address entry.UIKeyboardTypeDecimalPad, // A number pad with a decimal point.UIKeyboardTypeTwitter, // A type optimized for twitter text entry (easy access to @ #)UIKeyboardTypeWebSearch, // A default keyboard type with URL-oriented addition.UIKeyboardTypeAlphabet = UIKeyboardTypeASCIICapable, // Deprecated*/textField.keyboardType = UIKeyboardTypeDefault;// 設置返回鍵樣式/*UIReturnKeyDefault,UIReturnKeyGo,UIReturnKeyGoogle,UIReturnKeyJoin,UIReturnKeyNext,UIReturnKeyRoute,UIReturnKeySearch,UIReturnKeySend,UIReturnKeyYahoo,UIReturnKeyDone,UIReturnKeyEmergencyCall,UIReturnKeyContinue NS_ENUM_AVAILABLE_IOS(9_0),*/textField.returnKeyType = UIReturnKeyJoin;// 設置輸入的字母大小寫模式/*UITextAutocapitalizationTypeNone,UITextAutocapitalizationTypeWords,UITextAutocapitalizationTypeSentences,UITextAutocapitalizationTypeAllCharacters,*/textField.autocapitalizationType = UITextAutocapitalizationTypeWords;// 設置左右視圖顯示模式/*不設置模式,左右視圖顯示不出來UITextFieldViewModeNever,UITextFieldViewModeWhileEditing,UITextFieldViewModeUnlessEditing,UITextFieldViewModeAlways*/textField.leftViewMode = UITextFieldViewModeAlways;textField.rightViewMode = UITextFieldViewModeAlways;// 設置左右視圖textField.leftView = label1;textField.rightView = label2;// 讓 textField 獲取第一響應/*打開應用程序或界面時直接彈出鍵盤*/[textField becomeFirstResponder];// 讓 textField 放棄第一響應/*收起鍵盤*/[textField resignFirstResponder]; // 設置 textField 的代理,需遵守協議 <UITextFieldDelegate>textField.delegate = self;Swift
// 設置邊框樣式/*case None 無邊框,默認case Line 直線邊框case Bezel 邊框 + 陰影case RoundedRect 圓角矩形邊框*/textField.borderStyle = .Line// 設置背景顏色/*默認是透明的*/textField.backgroundColor = UIColor.yellowColor()// 設置背景圖片textField.background = UIImage(named: "pic2")// 設置提示文字/*用戶輸入時自動消失*/textField.placeholder = "請輸入用戶名"// 設置輸入的字體顏色textField.textColor = UIColor.redColor()// 設置文字對齊方式textField.textAlignment = NSTextAlignment.Left// 設置最小可縮小的字號textField.minimumFontSize = 10// 自動調整文字大小/*自動調整文字的大小以適應 textField 的寬度*/textField.adjustsFontSizeToFitWidth = true// 設置密文輸入模式/*default is NO*/textField.secureTextEntry = true// 設置顯示清除按鈕/*case Never // defaultcase WhileEditingcase UnlessEditingcase Always*/textField.clearButtonMode = .WhileEditing// 設置鍵盤樣式/*case Default // Default type for the current input method.case ASCIICapable // Displays a keyboard which can enter ASCII characters, // non-ASCII keyboards remain activecase NumbersAndPunctuation // Numbers and assorted punctuation.case URL // A type optimized for URL entry.case NumberPad // A number pad (0-9). Suitable for PIN entry.case PhonePad // A phone pad (1-9, *, 0, #, with letters under the numbers).case NamePhonePad // A type optimized for entering a person's name or phone number.case EmailAddress // A type optimized for multiple email address entry.case DecimalPad // A number pad with a decimal point.case Twitter // A type optimized for twitter text entry (easy access to @ #)case WebSearch // A default keyboard type with URL-oriented addition.public static var Alphabet: UIKeyboardType { get } // Deprecated*/textField.keyboardType = .Default// 設置返回鍵樣式/*case Defaultcase Gocase Googlecase Joincase Nextcase Routecase Searchcase Sendcase Yahoocase Donecase EmergencyCallcase Continue*/textField.returnKeyType = .Join// 設置輸入的字母大小寫模式/*case Nonecase Wordscase Sentencescase AllCharacters*/textField.autocapitalizationType = .Words// 設置左右視圖顯示模式/*不設置模式,左右視圖顯示不出來case Nevercase WhileEditingcase UnlessEditingcase Always*/textField.leftViewMode = .AlwaystextField.rightViewMode = .Always// 設置左右視圖textField.leftView = label1textField.rightView = label2// 讓 textField 獲取第一響應/*打開應用程序或界面時直接彈出鍵盤*/textField.becomeFirstResponder()// 讓 textField 放棄第一響應/*收起鍵盤*/textField.resignFirstResponder()// 設置 textField 的代理,需遵守協議 UITextFieldDelegatetextField.delegate = self
3、textField 協議方法
協議方法,需遵守協議 UITextFieldDelegate,并設置代理
Objective-C
// 將要開始編輯,編輯開始前被調用- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {return YES;}// 已經開始編輯,編輯開始后被調用,可監聽鍵盤的彈出- (void)textFieldDidBeginEditing:(UITextField *)textField {}// 將要結束編輯,編輯結束前被調用- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {return YES;}// 已經結束編輯,編輯結束后被調用,可監聽鍵盤的回收- (void)textFieldDidEndEditing:(UITextField *)textField {// 輸出 textfield 中輸入的內容NSLog(@"您輸入的內容為:%@", textField.text);}// 是否允許文本修改,文本修改前被調用/*NO 不允許輸入,YES 允許輸入(默認)range:光標范圍string:當前輸入的內容*/- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {return YES;}// 返回,鍵盤上的 return 鍵觸摸后調用- (BOOL)textFieldShouldReturn:(UITextField *)textField {return YES;}// 清空,文本輸入框中清除按鈕被觸摸時調用- (BOOL)textFieldShouldClear:(UITextField *)textField {return YES;}Swift
// 將要開始編輯,編輯開始前被調用func textFieldShouldBeginEditing(textField: UITextField) -> Bool {return true}// 已經開始編輯,編輯開始后被調用,可監聽鍵盤的彈出func textFieldDidBeginEditing(textField: UITextField) {}// 將要結束編輯,編輯結束前被調用func textFieldShouldEndEditing(textField: UITextField) -> Bool {return true}// 已經結束編輯,編輯結束后被調用,可監聽鍵盤的回收func textFieldDidEndEditing(textField: UITextField) {// 輸出 textfield 中輸入的內容print("您輸入的內容為:\(textField.text)") }// 是否允許文本修改,文本修改前被調用/*false 不允許輸入,true 允許輸入(默認)range:光標范圍string:當前輸入的內容*/func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {return true}// 返回,鍵盤上的 return 鍵觸摸后調用func textFieldShouldReturn(textField: UITextField) -> Bool {return true}// 清空,文本輸入框中清除按鈕被觸摸時調用func textFieldShouldClear(textField: UITextField) -> Bool {return true}
4、textField 的鍵盤回收
Objective-C
觸摸手勢回收
- 用觸摸手勢或表格滾動方式回收鍵盤,觸摸界面或滾動表格視圖時鍵盤消失
return 鍵回收
- 用代理方式回收鍵盤(鍵盤上的 return 鍵回收鍵盤),需遵守協議 UITextFieldDelegate,并設置代理
Swift
觸摸手勢回收
- 用觸摸手勢或表格滾動方式回收鍵盤,觸摸界面或滾動表格視圖時鍵盤消失
return 鍵回收
- 用代理方式回收鍵盤(鍵盤上的 return 鍵回收鍵盤),需遵守協議 UITextFieldDelegate,并設置代理
5、textField 視圖的上升/下降
Objective-C
用系統觀察者控制
可以獲取到鍵盤的高度和鍵盤彈起和隱藏的時間
多個觀察者
// 添加系統通知觀察者(檢測鍵盤的顯示與隱藏)// 檢測鍵盤的彈起[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShow:) name:UIKeyboardWillShowNotification object:nil];// 檢測鍵盤的隱藏 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHide:) name:UIKeyboardWillHideNotification object:nil];// 鍵盤彈起事件處理- (void)keyboardShow:(NSNotification *)notification {// 取出鍵盤最終的高度CGFloat keyboardHeight = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;// 取出鍵盤彈出需要花費的時間double duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];// 設置當前視圖的 frameCGRect frame = self.view.frame;frame.origin.y = -keyboardHeight;[UIView animateWithDuration:duration animations:^{self.view.frame = frame;}];}// 鍵盤隱藏事件處理- (void)keyboardHide:(NSNotification *)notification {// 取出鍵盤彈出需要花費的時間double duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];// 設置當前視圖的 frameCGRect frame = self.view.frame;frame.origin.y = 0;[UIView animateWithDuration:duration animations:^{self.view.frame = frame;}];}單一觀察者
// 添加系統通知觀察者(檢測鍵盤的 frame 改變)[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];// 鍵盤彈起隱藏事件處理- (void)keyboardWillChangeFrame:(NSNotification *)notification {// 取出鍵盤最終的 frameCGRect rect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];// 取出鍵盤彈出需要花費的時間double duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];// 設置當前視圖的 frameCGRect frame = self.view.frame;frame.origin.y = -([UIScreen mainScreen].bounds.size.height - rect.origin.y);[UIView animateWithDuration:duration animations:^{self.view.frame = frame;}];}視圖上升或下降處理
設置 frame
CGRect frame = self.view.frame;frame.origin.y = -keyboardHeight;[UIView animateWithDuration:duration animations:^{self.view.frame = frame;}];設置 約束值
self.bottomSpacing.constant = rect.size.height;[UIView animateWithDuration:duration animations:^{[self.view layoutIfNeeded];}];設置 transform 屬性
[UIView animateWithDuration:duration animations:^{CGFloat ty = [UIScreen mainScreen].bounds.size.height - rect.origin.y;self.view.transform = CGAffineTransformMakeTranslation(0, -ty);}];
用協議方法控制
// 開始編輯- (void)textFieldDidBeginEditing:(UITextField *)textField {// 獲取當前視圖的 frameCGRect frame = self.view.frame;frame.origin.y = -53;[UIView animateWithDuration:0.5 animations:^{self.view.frame = frame;}];}// 結束編輯- (void)textFieldDidEndEditing:(UITextField *)textField {CGRect frame = self.view.frame;frame.origin.y = 0;[UIView animateWithDuration:0.5 animations:^{self.view.frame = frame;}];}
Swift
用系統觀察者控制
可以獲取到鍵盤的高度和鍵盤彈起和隱藏的時間
多個觀察者
// 添加系統通知觀察者(檢測鍵盤的顯示與隱藏)// 檢測鍵盤的彈起NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(UiTextField.keyboardShow(_:)), name: UIKeyboardWillShowNotification, object: nil)// 檢測鍵盤的隱藏NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(UiTextField.keyboardHide(_:)), name: UIKeyboardWillHideNotification, object: nil)// 鍵盤彈起事件處理func keyboardShow(notification:NSNotification) {// 取出鍵盤最終的高度let keyboardHeight:CGFloat = (notification.userInfo![UIKeyboardFrameEndUserInfoKey]?.CGRectValue().size.height)!// 取出鍵盤彈出需要花費的時間let duration:Double = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue// 設置當前視圖的 framevar frame:CGRect = self.view.frameframe.origin.y = -keyboardHeightUIView.animateWithDuration(duration) {self.view.frame = frame}}// 鍵盤隱藏事件處理func keyboardHide(notification:NSNotification) {// 取出鍵盤彈出需要花費的時間let duration:Double = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue// 設置當前視圖的 framevar frame:CGRect = self.view.frameframe.origin.y = 0UIView.animateWithDuration(duration) {self.view.frame = frame}}單一觀察者
// 添加系統通知觀察者(檢測鍵盤的 frame 改變)NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(UiTextField.keyboardWillChangeFrame(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)// 鍵盤彈起隱藏事件處理func keyboardWillChangeFrame(notification:NSNotification) {// 取出鍵盤最終的高度let rect:CGRect = (notification.userInfo![UIKeyboardFrameEndUserInfoKey]?.CGRectValue())!// 取出鍵盤彈出需要花費的時間let duration:Double = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue// 設置當前視圖的 framevar frame:CGRect = self.view.frameframe.origin.y = -(UIScreen.mainScreen().bounds.size.height - rect.origin.y)UIView.animateWithDuration(duration) {self.view.frame = frame}}視圖上升或下降處理
設置 frame
var frame:CGRect = self.view.frameframe.origin.y = -keyboardHeightUIView.animateWithDuration(duration) {self.view.frame = frame}設置 約束值
self.bottomSpacing.constant = rect.size.heightUIView.animateWithDuration(duration) {self.view.layoutIfNeeded()}設置 transform 屬性
UIView.animateWithDuration(duration) { let ty:CGFloat = UIScreen.mainScreen().bounds.size.height - rect.origin.yself.view.transform = CGAffineTransformMakeTranslation(0, -ty)}
用協議方法控制
// 開始編輯func textFieldDidBeginEditing(textField: UITextField) {// 獲取當前視圖的 framevar frame:CGRect = self.view.frameframe.origin.y = -53UIView.animateWithDuration(0.5) {self.view.frame = frame}}// 結束編輯func textFieldDidEndEditing(textField: UITextField) {var frame:CGRect = self.view.frameframe.origin.y = 0UIView.animateWithDuration(0.5) {self.view.frame = frame}}
6、計算鍵盤高度
不同型號的 iOS 設備的鍵盤尺寸:
Type | iPhone 6(s) Plus | iPhone 6(s) | iPhone 5(s/c)/4(s)/SE------------------------|:----------------:|:------------:|:-----------------------:
Default | | |
ASCIICapable | | |
NumbersAndPunctuation | | |
URL | 271 | 258 | 253
EmailAddress | | |
Twitter | | |
WebSearch | | |
Alphabet | | |
------------------------|------------------|--------------|-------------------------
NumberPad | | |
PhonePad | 226 | 216 | 216
NamePhonePad | | |
DecimalPad | | |Objective-C
// 在系統觀察者響應方法中,獲取觀察的信息NSDictionary *userInfo = notification.userInfo;CGFloat keyboardHeight = [userInfo[@"UIKeyboardFrameEndUserInfoKey"] CGRectValue].size.height;Swift
// 在系統觀察者響應方法中,獲取觀察的信息let userInfo = notification.userInfo!let keyboardHeight = userInfo["UIKeyboardFrameEndUserInfoKey"]?.CGRectValue().size.height
7、Storyboard 中設置
在 Storyboard 場景中設置
Text Field 設置
Text | 文字類型及文字-------------------------------|-------------------
Color | 文字顏色
Font | 文字字體
Alignment | 文字對齊方式
Placeholder | 占位文字
|
Background | 背景圖片
Disabled | 無效狀態背景圖片
|
Border Style | 邊框類型
|
Clear Button | 清除按鈕顯示時間
-- Clear when editing begins | 開始編輯時顯示清楚按鈕
|
Min Font Size | 最小字體大小
-- Adjust to Fit | 自動調整文字大小
|
Capitalization | 大小寫模式
Correction | 自動糾正
Spell Checking | 拼寫檢查
Keyboard Type | 鍵盤樣式
Appearance |
Return Key | 返回鍵樣式
-- Auto-enable Return Key | 自動使能返回鍵
-- Secure Text Entry | 密文輸入Control 設置
Alignment | 文字對齊方式-------------------------------|-------------------
Content |
-- Selected | 選中
-- Enable | 可用
-- Highlighted | 高亮
轉載于:https://www.cnblogs.com/QianChia/p/5754504.html
總結
以上是生活随笔為你收集整理的iOS - UITextField的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据库设计五要点 让数据库设计更加规范
- 下一篇: 【Win10】UAP/UWP/通用 开发