在开发过程中,可能会遇到这样的问题,页面中有textView或者textField,且放置在屏幕的下方,当点击它们进行输入时,发现它们会被键盘挡住,导致用户看不见自己输入的内容,如图所示:
这种效果显然是需要改进的。那么如何能让用户看见自己的输入内容呢?解决方法如下:
1.监听键盘
在.m文件中的viewDidLoad方法中添加监听
[[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(keyboardWillShow:)name:UIKeyboardWillShowNotificationobject:nil];
[[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(keyboardWillHide:)name:UIKeyboardWillHideNotificationobject:nil];
//配置Iphone5的
#ifdef __IPHONE_5_0
float version = [[[UIDevicecurrentDevice] systemVersion] floatValue];
if (version >= 5.0) {
[[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(keyboardWillShow:)name:UIKeyboardWillChangeFrameNotificationobject:nil];
}
#endif
2.获取键盘的高度
- (void)keyboardWillShow:(NSNotification *)notification{
NSDictionary *info = [notification userInfo];
float i= [[infoobjectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue].size.height;//得到键盘的高度
[selfletViewUp:i];//让当前屏幕抬高
}
//抬高当前屏幕
- (void)letViewUp:(float) h{
self.view.frame=CGRectMake(self.view.frame.origin.x,-h, self.view.frame.size.width,self.view.frame.size.height);
}
效果图如下:
此时屏幕被抬高,用户可以看见自己输入的内容
//恢复屏幕高度,当输入完成以后一定不要忘了恢复键盘的高度
-(void)keyboardWillHide:(NSNotification *)notification{
[selftableViewDown];
}
- (void)tableViewDown{
self.view.frame=CGRectMake(self.view.frame.origin.x,0,self.view.frame.size.width,self.view.frame.size.height);
}
再次要添加个让键盘消失的方法,否则键盘不会下来
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[textFieldresignFirstResponder];
}
效果图如下:此时屏幕又回到原来的高度