假设这样一个界面,中间那个面面积大的控件是UITextView,当屏幕下方的UITextFile被选中,弹出软键盘时,键盘将遮住其下方原来屏幕的内容,此时就需要采取一些方法来动态修改键盘弹出时,程序的界面。
1、获取键盘的高度:
关于键盘的高度,网上有很多的版本,大多将其理解为一个固定的值。其实键盘的高度是变化的,在输入中文的时候,会比输入英文的时候高,因为键盘还多了一行用于显示词汇的联想。正确获取键盘高度的方法如下:
注册UIKeyboardDidShowNotification和UIKeyboardDidHideNotification
- (void) registerForKeyboardNotifications{ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardDidHideNotification object:nil]; }
实现相关的selector:
- (void) keyboardWasShown:(NSNotification *) notif{ // 获取notif中附带的键盘的信息 NSDictionary *info = [notif userInfo]; NSValue *value = [info objectForKey:UIKeyboardBoundsUserInfoKey]; //keyboardSize中包含了键盘的大小 CGSize keyboardSize = [value CGRectValue].size; //根据获取的高度keyboardSize.height 进行对UI的修改,以下代码的效果如下图 msgTextView.frame = CGRectMake(5.0f, 80.0f, 310.0f, (326.0-keyboardSize.height+20)); msgToSend.frame=CGRectMake(4.0f, 418.0-keyboardSize.height+10, 231, 31); sendMsgToSocketServer.frame=CGRectMake(243, 418.0-keyboardSize.height+10, 72.0, 31.0); msgTextView.selectedRange = NSMakeRange([msgTextView.text length], 0); [msgTextView scrollRangeToVisible: msgTextView.selectedRange]; } - (void) keyboardWasHidden:(NSNotification *) notif{ // 将UI恢复到键盘弹出前的布局 msgTextView.frame = CGRectMake(5.0f, 80.0f, 310.0f, 326.0f); msgToSend.frame=CGRectMake(4.0f, 418.0f, 231, 31); sendMsgToSocketServer.frame=CGRectMake(243, 418.0f, 72.0, 31.0); msgTextView.selectedRange = NSMakeRange([msgTextView.text length], 0); [msgTextView scrollRangeToVisible: msgTextView.selectedRange]; }
键盘弹出时的界面: