您的位置:首页 > 其它

245,键盘处理

2016-02-10 22:48 417 查看

1,键盘

在IOS开发中使用UITextField时常需要考虑的问题就是键盘的处理。有时候,弹出的键盘会将UITextField区域覆盖,影响用户输入。

这个时候就要将视图上移。这个时候我们需要考虑两点: 1,修改视图坐标的时机; 2,上移的偏移是多大。 3,UITableView设置Section间距 不明白的可以看看。

我根据自己实际操作的实现方法如下: 1,获取正在编辑的UITextField的指针 定义一个全局的UITextField的指针 UITextField *tempTextFiled; 在UITextFieldDelegate代理方法-(void)textFieldDidBeginEditing:(UITextField *)textField中 修正tempTextFiled的值为当前正在编辑的UITextField的地址。 -(void)textFieldDidBeginEditing:(UITextField
*)textField { tempTextFiled = textField; }

2,配置键盘处理事件

在- (void)viewDidLoad中实现键盘监听: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil]; 实现键盘显示和键盘隐藏方法 在键盘显示方法中获取键盘高度,并配置键盘视图位移【值得一提的是,该方法会在用户切换中英文输入法的时候也会执行,因此不必担心在切换到中文输入法时键盘有多出一部分的问题】。 - (void)keyboardWillShow:(NSNotification *)notification

{

NSDictionary * info = [notification userInfo];

NSValue *avalue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];

CGRect keyboardRect = [self.view convertRect:[avalue CGRectValue] fromView:nil];

double keyboardHeight=keyboardRect.size.height;//键盘的高度

NSLog(@"textField superview].frame.origin.y = %f",[tempTextFiled superview].frame.origin.y);

NSLog(@"keyboardHeight = %f",keyboardHeight);

if ( ([tempTextFiled superview].frame.origin.y + keyboardHeight + REGISTERTABLE_CELL_HEGHIT) >= ([[UIScreen mainScreen] bounds].size.height-44))

{

//此时,编辑框被键盘盖住,则对视图做对应的位移

CGRect frame = CGRectMake(0, 44, 320, [[UIScreen mainScreen] bounds].size.height-45);

frame.origin.y -= [tempTextFiled superview].frame.origin.y + keyboardHeight + REGISTERTABLE_CELL_HEGHIT +20 - [[UIScreen mainScreen] bounds].size.height + 44;//偏移量=编辑框原点Y值+键盘高度+编辑框高度-屏幕高度

registerTableView.frame=frame;

}

} 然后实现键盘隐藏的处理: 在UITextFieldDelegate代理方法 -(void)textFieldDidEndEditing:(UITextField *)textFieldView或者 - (void)keyboardWillHide:(NSNotification *)notification 方法中实现视图复位,如下代码: CGRect frame = registerTableView.frame; frame.origin.y = 44;//修改视图的原点Y坐标即可。 registerTableView.frame=frame;

3,移除监听

在-(void)viewDidDisappear:(BOOL)animated或者dealloc方法中移除监听 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil]; [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification
object:nil]; 这样,无论我们的界面上有多少UITextField,只需要简单的几部就可以实现UITextField不被键盘盖住。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: