转自http://blog.youkuaiyun.com/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;
- }