虚拟键盘弹出挡住textfield的分析以及解决办法

转自http://blog.csdn.net/u011374699/article/details/45894303

原本用的方法是int offset = textfield.frame.origin.y + height - self.view.frame.size.height  + 216(键盘高度)来计算y轴移动的偏移量。如果offset大于0,就向上偏移。

这里有个问题:如果textfield所在view外面嵌套了好多层布局,而且使用autoLayout,那么,textfield.frame.origin.y=0,导致offset小于0而没有向上偏移。

以下是经本人测试且有效的办法:

  1. // 开始编辑输入框时,键盘出现,视图的Y座标向上移动offset个单位,腾出空间显示键盘  
  2. - (void)textFieldDidBeginEditing:(UITextField *)textField  
  3. {  
  4.       
  5.     CGRect textFrame = textField.frame;  
  6.     CGPoint textPoint = [textField convertPoint:CGPointMake(0, textField.frame.size.height) toView:self.view];// 关键的一句,一定要转换  
  7.     int offset = textPoint.y + textFrame.size.height + 216 - self.view.frame.size.height + 24;// 24是textfield和键盘上方的间距,可以自由设定  
  8.   
  9.     NSTimeInterval animationDuration = 0.30f;  
  10.     [UIView beginAnimations:@"ResizeForKeyboard" context:nil];  
  11.     [UIView setAnimationDuration:animationDuration];  
  12.       
  13.     // 将视图的Y座标向上移动offset个单位,以使下面腾出地方用于软键盘的显示  
  14.     if (offset > 0) {  
  15.         self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.widthself.view.frame.size.height);  
  16.     }  
  17.       
  18.     [UIView commitAnimations];  
  19. }  
  20.   
  21. // 用户输入时  
  22. - (BOOL)textFieldShouldEndEditing:(UITextField *)textField{  
  23.     // 输入结束后,将视图恢复到原始状态  
  24.     self.view.frame = CGRectMake(00self.view.frame.size.widthself.view.frame.size.height);  
  25.     return YES;  


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章