前言
NS_CLASS_AVAILABLE_IOS(2_0) @interface UITextField : UIControl <UITextInput, NSCoding>@available(iOS 2.0, *) public class UITextField : UIControl, UITextInput, NSCoding
1、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
触摸手势回收
- 用触摸手势或表格滚动方式回收键盘,触摸界面或滚动表格视图时键盘消失
// 单一 textField 回收键盘// 让 textField 放弃第一响应,收起键盘[textField resignFirstResponder];// 所有 textField 都回收键盘[self.view endEditing:YES];
return 键回收
- 用代理方式回收键盘(键盘上的 return 键回收键盘),需遵守协议 UITextFieldDelegate,并设置代理
// 设置 textField 的代理textField1.delegate = self;textField2.delegate = self;// UITextFieldDelegate 协议方法返回,键盘上的 return 键点击后调用 - (BOOL)textFieldShouldReturn:(UITextField *)textField {UITextField *textField_1 = (id)[self.view viewWithTag:200];UITextField *textField_2 = (id)[self.view viewWithTag:300];if (textField == textField_1) {// 让 textField_2 获取第一响应// 点击 textfield_1 上的 return 键时,输入光标自动跳转到 textfield_2 内[textField_2 becomeFirstResponder];}else{// 让 textField_2 放弃第一响应// 点击 textfield_2 上的 return 键时,键盘回收[textField_2 resignFirstResponder];}return YES;}
Swift
触摸手势回收
- 用触摸手势或表格滚动方式回收键盘,触摸界面或滚动表格视图时键盘消失
// 单一 textField 回收键盘// 让 textField 放弃第一响应,收起键盘textField.resignFirstResponder()// 所有 textField 都回收键盘self.view.endEditing(true)
return 键回收
- 用代理方式回收键盘(键盘上的 return 键回收键盘),需遵守协议 UITextFieldDelegate,并设置代理
// 设置 textField 的代理textField1.delegate = selftextField2.delegate = self// UITextFieldDelegate 协议方法返回,键盘上的 return 键点击后调用func textFieldShouldReturn(textField: UITextField) -> Bool {let textField_1:UITextField = self.view.viewWithTag(200) as! UITextFieldlet textField_2:UITextField = self.view.viewWithTag(300) as! UITextFieldif textField == textField_1 {// 让 textField_2 获取第一响应// 点击 textfield_1 上的 return 键时,输入光标自动跳转到 textfield_2 内textField_2.becomeFirstResponder()}else{// 让 textField_2 放弃第一响应,点击 textfield_2 上的 return 键时,键盘回收textField_2.resignFirstResponder()}return true}
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 | 高亮