您的位置:首页 > 其它

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

2017-03-01 16:36 387 查看
转自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而没有向上偏移。

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

// 开始编辑输入框时,键盘出现,视图的Y坐标向上移动offset个单位,腾出空间显示键盘  
- (void)textFieldDidBeginEditing:(UITextField *)textField  
{  
      
    CGRect textFrame = textField.frame;  
    CGPoint textPoint = [textField convertPoint:CGPointMake(0, textField.frame.size.height) toView:self.view];// 关键的一句,一定要转换  
    int offset = textPoint.y + textFrame.size.height + 216 - self.view.frame.size.height + 24;// 24是textfield和键盘上方的间距,可以自由设定  
  
    NSTimeInterval animationDuration = 0.30f;  
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];  
    [UIView setAnimationDuration:animationDuration];  
      
    // 将视图的Y坐标向上移动offset个单位,以使下面腾出地方用于软键盘的显示  
    if (offset > 0) {  
        self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);  
    }  
      
    [UIView commitAnimations];  
}  
  
// 用户输入时  
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{  
    // 输入结束后,将视图恢复到原始状态  
    self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);  
    return YES;  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: