iOS - UITextField
前言
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, // default
UITextFieldViewModeWhileEditing,
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 active
UIKeyboardTypeNumbersAndPunctuation, // 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 // default
case WhileEditing
case UnlessEditing
case 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 active
case 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 Default
case Go
case Google
case Join
case Next
case Route
case Search
case Send
case Yahoo
case Done
case EmergencyCall
case Continue
*/
textField.returnKeyType = .Join // 设置输入的字母大小写模式
/*
case None
case Words
case Sentences
case AllCharacters
*/
textField.autocapitalizationType = .Words // 设置左右视图显示模式
/*
不设置模式,左右视图显示不出来 case Never
case WhileEditing
case UnlessEditing
case Always
*/
textField.leftViewMode = .Always
textField.rightViewMode = .Always // 设置左右视图
textField.leftView = label1
textField.rightView = label2 // 让 textField 获取第一响应
/*
打开应用程序或界面时直接弹出键盘
*/
textField.becomeFirstResponder() // 让 textField 放弃第一响应
/*
收起键盘
*/
textField.resignFirstResponder() // 设置 textField 的代理,需遵守协议 UITextFieldDelegate
textField.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 = self
textField2.delegate = self // UITextFieldDelegate 协议方法返回,键盘上的 return 键点击后调用
func textFieldShouldReturn(textField: UITextField) -> Bool { let textField_1:UITextField = self.view.viewWithTag(200) as! UITextField
let textField_2:UITextField = self.view.viewWithTag(300) as! UITextField if 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]; // 设置当前视图的 frame
CGRect 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]; // 设置当前视图的 frame
CGRect 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 { // 取出键盘最终的 frame
CGRect rect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue]; // 取出键盘弹出需要花费的时间
double duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue]; // 设置当前视图的 frame
CGRect 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 { // 获取当前视图的 frame
CGRect 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 // 设置当前视图的 frame
var frame:CGRect = self.view.frame
frame.origin.y = -keyboardHeight UIView.animateWithDuration(duration) {
self.view.frame = frame
}
} // 键盘隐藏事件处理
func keyboardHide(notification:NSNotification) { // 取出键盘弹出需要花费的时间
let duration:Double = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue // 设置当前视图的 frame
var frame:CGRect = self.view.frame
frame.origin.y = 0 UIView.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 // 设置当前视图的 frame
var frame:CGRect = self.view.frame
frame.origin.y = -(UIScreen.mainScreen().bounds.size.height - rect.origin.y) UIView.animateWithDuration(duration) {
self.view.frame = frame
}
}
视图上升或下降处理
设置 frame
var frame:CGRect = self.view.frame
frame.origin.y = -keyboardHeight
UIView.animateWithDuration(duration) {
self.view.frame = frame
}
设置 约束值
self.bottomSpacing.constant = rect.size.height
UIView.animateWithDuration(duration) {
self.view.layoutIfNeeded()
}
设置 transform 属性
UIView.animateWithDuration(duration) {
let ty:CGFloat = UIScreen.mainScreen().bounds.size.height - rect.origin.y
self.view.transform = CGAffineTransformMakeTranslation(0, -ty)
}
用协议方法控制
// 开始编辑
func textFieldDidBeginEditing(textField: UITextField) { // 获取当前视图的 frame
var frame:CGRect = self.view.frame
frame.origin.y = -53 UIView.animateWithDuration(0.5) {
self.view.frame = frame
}
} // 结束编辑
func textFieldDidEndEditing(textField: UITextField) { var frame:CGRect = self.view.frame
frame.origin.y = 0 UIView.animateWithDuration(0.5) {
self.view.frame = frame
}
}
6、计算键盘高度
不同型号的 iOS 设备的键盘尺寸:
Type | iPhone 6(s) Plus | iPhone 6(s) | iPhone 5(s/c)/4(s)/SE
------------------------|:----------------
iOS - UITextField的更多相关文章
- IOS UITextField &UITextView
UITextField 限制textField长度 曾经,以为输入框只是输入字符的,但真的认真为一个登陆界面输入框而改了六七次以后,发现好烦人啊,先谢谢测试的不厌其烦,不杀之恩,不想再用IOS的输入框 ...
- iOS UITextField的代理<UITextFieldDelegate>的几点笔记
今天做项目的时候,有个需求,点击按钮,就在特定的编辑框输入按钮中的文字,一开始我还以C++的思想来写,先获取光标的位置,然后在判断是否在那个编辑框,进行输入.后来我旁边的同事看到了直接教我用代理方法, ...
- 简单几步实现 IOS UITextField输入长度的控制
在ios开发过程中,我们有时候需要对UITextField的输入长度进行控制,比如输入手机号码最大长度为11位等,而ios自身又不像android那样可以设置输入框的输入长度,接下来通过简单几步实现这 ...
- iOS UITextField限制输入字数
关于iOS的文本框有时需要限制字数,如手机号,在UITextField的代理单纯写一个判断,在字数超过限制时,这时再想删除就删除不掉,可以在代理这样写,就解决 - (BOOL)textField:(U ...
- iOS UITextField限制输入数字
有时候项目中要求文本框中只能输入数字,如:价格.公里数.费用等等,一般的文本框不限制输入的格式,这时候只能强制限制输入框的输入格式了,代码如下: #import "ViewControlle ...
- iOS - UITextfield 验证邮箱格式
做登录界面时,用户在UITextfield中输入输入邮箱账号后,我们应该在本地验证格式是否正确,再将参数传给服务器验证. 最简单的就是利用系统的NSPredicate //利用正则表达式验证 -(BO ...
- iOS UITextField的returnkey点击事件
关于隐藏软键盘,网上的办法良莠不齐,大多是通过实现UITextFieldDelegate来隐藏软键盘,该方法代码较多,且在文本框很多的时不好处理.我经过搜索与摸索,找到了最佳的处理办法.(引用的) ...
- iOS UITextField 输入字数限制的实现
首先你的ViewController需要实现 UITextFieldDelegate 代理, 其次,需要字数限制的UITextField实例的代理要设置成 self(ViewController) 然 ...
- iOS UITextField 响应键盘的return 事件
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(, , , )] textField.returnKeyT ...
随机推荐
- Oracle通过sqlplus spool导入导出数据
第一部分(实例,主要分两步),第二部分(参数小总结),第三部分(完全参数总结) 第一部分 第一步 :这是我的导出数据的脚本call.sqlconn scott/tigerset echo offset ...
- RMAN笔记小结
首先感谢junsansi和leshani两位大师的文笔:我可是好好看了很多遍:这两位哦:我跟你们说:对rman的解说那是相当精彩:文章形如流水,通俗易懂:内容那是入木三分...;好了我也不多说了,反正 ...
- 自己封装的OKhttp请求
package com.create.qdocumentimtest.rxjavatest; import com.squareup.okhttp.Callback; import com.squar ...
- MySQL数据类型总结
MySQL中的数据类型大的方面来分,可以分为:日期和时间.数值,以及字符串.下面就分开来进行总结. 日期和时间数据类型 MySQL数据类型 含义 date 3字节,日期,格式:2014-09-18 t ...
- [ios][opengles]OpenGL ES基础知识简介
参考: http://www.cnblogs.com/shangdahao/archive/2011/11/05/2233587.html 3D变换:模型,视图,投影与Viewport: http:/ ...
- ie6下兼容问题
最小高度问题:overflow:hidden 在ie6.7下 li本身不浮动 内容浮动 li产生3像素间隙 解决:vertical-align:top; 二.当ie6下最小高度问题和li间隙问题共存时 ...
- 20150604_Andriod 窗体PopupWindow
package com.example.test1; import android.support.v7.app.ActionBarActivity;import android.os.Bundle; ...
- C#实现中国天气网XML接口测试
点击链接查看中国天气网接口说明,最近想研究一下接口测试,源于最近一次和某公司的技术总监(交大校友)谈话,发现接口测试的需求是比较大的,于是想要研究一下. 好不容易在网上找到了一个关于中国天气网的接口说 ...
- mysql 导入导出的几个常用参数
导出命令: mysqldump -t --skip-extended-insert -utest -p testdb tableA > testdb_tableA.sql 参数说明: -t: 仅 ...
- UML中的用例(Use Case)概念分析及StarUML实例
在UML中use case似 乎最簡單的,用例建模的最主要功能就是用来表达系统的功能性需求或行为,依我的理解用例建模可分为用例图和用例描述.用例图由参与者(Actor).用例 (Use Case).系 ...
- IOS UITextField &UITextView