为什么在显示键盘时视图向下移动?

时间:2014-10-01 13:22:47

标签: ios iphone xcode uitextview

我有一个基于标签控制器的应用程序,我有一个uitextview选择我在键盘出现时向上移动视图,整个工作正常,直到我切换标签,当我回到此选项卡并尝试在uitextview中编辑视图向下移动然后回到键盘上的正常位置而不是向上移动。这是整个代码

- (void)textViewDidBeginEditing:(UITextView *)textField
{
[self keyboardWillShow];

}
-(void)textViewDidEndEditing:(UITextView *)textField
{
[self keyboardWillHide];
}
 -(void)keyboardWillShow {
// Animate the current view out of the way
if (self.view.frame.origin.y >= 0)
{
    [self setViewMovedUp:YES];
}
else if (self.view.frame.origin.y < 0)
{
    [self setViewMovedUp:NO];
}
}

-(void)keyboardWillHide {
if (self.view.frame.origin.y >= 0)
{
    [self setViewMovedUp:YES];
}
else if (self.view.frame.origin.y < 0)
{
    [self setViewMovedUp:NO];
}
}
//method to move the view up/down whenever the keyboard is shown/dismissed
-(void)setViewMovedUp:(BOOL)movedUp
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5]; // if you want to slide up the view

CGRect rect = self.view.frame;
if (movedUp)
{
    // 1. move the view's origin up so that the text field that will be hidden come above the    keyboard
    // 2. increase the size of the view so that the area behind the keyboard is covered up.
    rect.origin.y -= kOFFSET_FOR_KEYBOARD;
    rect.size.height += kOFFSET_FOR_KEYBOARD;
}
else
{
    // revert back to the normal state.
    rect.origin.y += kOFFSET_FOR_KEYBOARD;
    rect.size.height -= kOFFSET_FOR_KEYBOARD;
}
self.view.frame = rect;

[UIView commitAnimations];
}

1 个答案:

答案 0 :(得分:0)

我有类似的问题,并想出来了。你可以查看我最近的帖子:

https://stackoverflow.com/a/28177645/2989374