iPhone - 如何在键盘出现时滚动UITextField并调整UITextView的大小

时间:2011-01-26 00:24:09

标签: iphone keyboard uitextfield scroll uitextview

我有一个UIScrollView里面有一个UITextField和一个UITextView。 我想阻止键盘隐藏我们正在处理的字段。 如果我的用户点击TextField,我希望它滚动到屏幕顶部。 如果我的用户点击TextView,我希望它调整大小到键盘顶部左侧的空白处。 我的键盘有一个附件视图(工具栏)。

现在,我抓住了UIKeyboardWillShowNotification通知,我使用的代码实际上并不起作用(textview已调整大小,但仍在键盘后面): 当我没有UIScrollView时,这段代码运行良好。

- (void)keyboardWillShow:(NSNotification *)notification {

    if ([self.noteView isFirstResponder] == NO) return;

    /*
     Reduce the size of the text view so that it's not obscured by the keyboard.
     Animate the resize so that it's in sync with the appearance of the keyboard.
     */

    NSDictionary *userInfo = [notification userInfo];
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];                            // Get the origin of the keyboard when it's displayed.
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];   // Get the duration of the animation.

    // Get the top of the keyboard as the y coordinate of its origin in self's view's coordinate system. The bottom of the text view's frame should align with the top of the keyboard's final position.
    CGRect keyboardRect = [aValue CGRectValue];
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];

    CGFloat keyboardTop = keyboardRect.origin.y;
    CGRect newTextViewFrame = self.view.bounds;
    newTextViewFrame.size.height = keyboardTop - self.view.frame.origin.y; // Using bounds here does not help

    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];

    // Animate the resize of the text view's frame in sync with the keyboard's appearance.
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];

     self.noteView.frame = newTextViewFrame;

    [UIView commitAnimations];
}

你能帮助我:

  • 为textview做这个工作吗?

  • 让Textview回到原来的位置?

  • 如何在没有任何调整大小功能的情况下滚动TextField?

谢谢

1 个答案:

答案 0 :(得分:0)

你能用编程方式滚动uiscrollview:

- (void)scrollRectToVisible:(CGRect)rect animated:(BOOL)animated

不确定这是否适用于您的应用程序。