1

我有一个 UIScrollView 包含一个文本字段和一个文本视图。当键盘存在时,我有代码可以向上移动文本字段,因此键盘不会覆盖文本字段。此代码在纵向视图中效果很好:

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    if(textField) {
        [textField resignFirstResponder];
    }
    return NO;
}

-(void)textFieldDidBeginEditing:(UITextField *)textField {
    if (textField == self.nameField) {
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDelegate:self];
        [UIView setAnimationDuration:0.3];
        [UIView setAnimationBeginsFromCurrentState:YES];
        self.view.frame = CGRectMake(self.view.frame.origin.x,   (self.view.frame.origin.y - 90), self.view.frame.size.width, self.view.frame.size.height);
        [UIView commitAnimations];
    }
}

-(void)textFieldDidEndEditing:(UITextField *)textField {
    if (textField == self.nameField) {
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDelegate:self];
        [UIView setAnimationDuration:0.3];
        [UIView setAnimationBeginsFromCurrentState:YES];
        self.view.frame = CGRectMake(self.view.frame.origin.x, (self.view.frame.origin.y + 90), self.view.frame.size.width, self.view.frame.size.height);
        [UIView commitAnimations];
    }
}

-(void)textViewDidBeginEditing:(UITextView *)textField {
    if (textField == self.questionField) {
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDelegate:self];
        [UIView setAnimationDuration:0.3];
        [UIView setAnimationBeginsFromCurrentState:YES];
        self.view.frame = CGRectMake(self.view.frame.origin.x, (self.view.frame.origin.y - 200), self.view.frame.size.width, self.view.frame.size.height);
        [UIView commitAnimations];
    }
}

-(void)textViewShouldEndEditing:(UITextView *)textField {
    if (textField == self.questionField) {
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDelegate:self];
        [UIView setAnimationDuration:0.3];
        [UIView setAnimationBeginsFromCurrentState:YES];
        UIInterfaceOrientation interfaceOrientation = self.interfaceOrientation;

        self.view.frame = CGRectMake(self.view.frame.origin.x, (self.view.frame.origin.y + 200), self.view.frame.size.width, self.view.frame.size.height);
        [UIView commitAnimations];
    }
}

当我将 iPhone 模拟器旋转到横向视图时,这(不足为奇)不起作用。在横向和纵向视图中输入文本时,如何让文本字段向上移动足以看到它?

此外,如果我在显示键盘时从横向旋转到纵向,则在关闭键盘后,滚动视图会在屏幕上向下移动,而不是在其原始位置排列。我怎样才能避免这种情况?

4

1 回答 1

2

Apple 的文档管理键盘在“移动位于键盘下方的内容”标题下显示了执行此操作的正确方法。

您基本上将您的内容放在滚动视图上,并使用UIKeyboardDidShowNotificationUIKeyboardWillHideNotification通知来调整内容偏移量。

但是,代码有些不完整。键盘大小计算在横向模式下不起作用。要修复它,请替换它:

CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

有了这个:

// Works in both portrait and landscape mode
CGRect kbRect = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
kbRect = [self.view convertRect:kbRect toView:nil];

CGSize kbSize = kbRect.size;
于 2013-08-07T18:02:25.330 回答