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

来源:互联网 发布:我的小公主 知乎 编辑:程序博客网 时间:2024/05/01 18:02


虚拟键盘弹出挡住textfield的问题,在网上搜出一大堆。但是很多方案也只是在某种情况下能满足我们的需求。

之前的做法是根据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;}

个人笔记,如果有不足的地方,欢迎大家一起讨论,一起进步。

转载请注明地址:http://blog.csdn.net/u011374699/article/details/45894303


0 0