文本框(UITextField)及键盘遮挡处理和回收
文本框属性
官网文档:UITextField Class Reference
以下都是可以在IB中选择设置的,也可以使用代码编写
placeholder :文本提示、提示符【placeholder:占位符】
aligment:对其方式
clear Button:清除按钮
键盘选项
default//默认键盘(没有特殊要求就选它)
keyboardeType:弹出键盘类型(自动的),列举几个陌生的NumbersAndPunctuation//数字和符号键盘
decimal Pad//带小数点的键盘
TypeTwitter//优化的键盘,方便输入@、#等特殊自符
其他若干中键盘方式
capitalization:输入框首字母是否大写
返回健有多种选项:其中emergency call为紧急呼叫
secure Text Entry:输入的字符影藏(像密码框一样)
swift版本编码方式创建文本框:文本框的基本使用
文本框代理和通知
官方文档:UItextFieldDelegateprotocol Reference
文本框代理:
public protocol UITextFieldDelegate : NSObjectProtocol {
@available(iOS 2.0, *)
optional public func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool // return NO to disallow editing.
@available(iOS 2.0, *)
optional public func textFieldDidBeginEditing(_ textField: UITextField) // became first responder
@available(iOS 2.0, *)
optional public func textFieldShouldEndEditing(_ textField: UITextField) -> Bool // return YES to allow editing to stop and to resign first responder status. NO to disallow the editing session to end
@available(iOS 2.0, *)
optional public func textFieldDidEndEditing(_ textField: UITextField) // may be called if forced even if shouldEndEditing returns NO (e.g. view removed from window) or endEditing:YES called
@available(iOS 10.0, *)
optional public func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason) // if implemented, called in place of textFieldDidEndEditing:
@available(iOS 2.0, *)
optional public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool // return NO to not change text
@available(iOS 2.0, *)
optional public func textFieldShouldClear(_ textField: UITextField) -> Bool // called when clear button pressed. return NO to ignore (no notifications) //清除按钮点击时调用 ,返回NO则忽略清除
@available(iOS 2.0, *)
optional public func textFieldShouldReturn(_ textField: UITextField) -> Bool // called when 'return' key pressed. return NO to ignore. //返回按钮被点击时,调用,返回true时会自动收起键盘
}
通知监听
文本框的开始和结束编辑,以及文本改变都是通过系统发出通知的。
通知如下:
extension NSNotification.Name {
public static let UITextFieldTextDidBeginEditing: NSNotification.Name
public static let UITextFieldTextDidEndEditing: NSNotification.Name
public static let UITextFieldTextDidChange: NSNotification.Name
}
可以在该页面监听通知,然后做出处理函数(比如在其中检查某些字段的合法性),
代码如下:
1。首先,注册通知(注意通知的名字是系统定义的,是系统发出的通知)
NotificationCenter.default.addObserver(self, selector: #selector(checkThePhoneNum), name:.UITextFieldTextDidChange, object: nil)
2.实现检查函数
//电话号码检查
func checkThePhoneNum(sender:Notification) -> Void {
phoneNumber = self.phoneNum.text!
let str = phoneNumber as NSString
if str.length>11 {
MBProgressHUD.failtureHUD(message: "电话超过11位", to: self.view)
}
}
3.取消通知注册
deinit {
NotificationCenter.default.removeObserver(self)
}
键盘回收
实现键盘回收,只需要在文本返回(textFieldShouldReturn)方法取消文本框(.resignFirstResponder())的第一响应
通用方法:在上一个视图中添加手势,在手势的Action函数中取消掉相应的文本框的第一相应。
提示:如果遇到模拟器点击文本框时不能显示键盘,在模拟器设置Hardware->KeyBoard->取消Connect hardwarekeyboard
键盘遮挡问题处理
针对文本输入框/视图,编辑时就会调用键盘,如果输入框在屏幕下方很有可能被弹出的键盘给遮挡住。
解决思想:根据是否遮挡输入框,对整个keyWindow是上移,从而避免遮挡,当然,还得使用通知。
具体代码实现(Object-C)
//ll键盘通知【learn】
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(showKeyboard:) name:UIKeyboardWillShowNotification object:nil]; //调用键盘时通知处理 <pre name="code" class="objc"> [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(hideKeyboard:) name:UIKeyboardWillHideNotification object:nil];//键盘回收通知处理
<pre name="code" class="objc">//ll获取通知中心的信息,键盘出现的时候
-(void) showKeyboard:(NSNotification*) noti{
NSDictionary *info = [noti userInfo];
NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
NSLog(@"输出以下这个集合看看有些什么:%i");
for (NSString *key in info) {//集合的遍历
NSLog(@"%@:%@",key,[info objectForKey:key]);
}
CGRect arect = [value CGRectValue];//注意基本数据不用*
_height = arect.size.height;
NSLog(@"键盘的高度:%f",self.height);
//思想:通过移动整个UIWindou
//1.获取文本框的相对位置
CGPoint relationPoint = [self.inputView convertPoint:CGPointZero toView:[UIApplication sharedApplication].keyWindow];
//2.计算活动面积高度
CGFloat actualHeight = CGRectGetHeight(self.inputView.frame) + relationPoint.y + self.height ;
//3.判断是否会发生键盘遮挡问题
CGFloat overstep = actualHeight - [UIScreen mainScreen].bounds.size.height;
if (overstep>0) {
//需要移动
CGRect frame = [UIScreen mainScreen].bounds;
frame.origin.y -= overstep; //[learn】主屏幕往上移动,初始坐标的y值是负的
//获取屏幕方向
CGFloat duration = [noti.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];//好好研读LL
[UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
//4.调整视图
[UIApplication sharedApplication].keyWindow.frame = frame;
} completion:nil];
}
//键盘回收处理,上移部分恢复,
-(void) hideKeyboard: (NSNotification*) noti{
CGFloat duration = [noti.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
CGRect frame = [UIScreen mainScreen].bounds;
[UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
NSLog(@"即将回收见盘");
[UIApplication sharedApplication].keyWindow.frame = frame;
} completion:nil];
}
提示:使用以上代码无法回收键盘?不知道为什么,调用resignFirstspoder总是返回NO值。希望知道的大神评论区告知原因。
UITextField的其他知识:自定义限制输入