键盘有时会阻止UITextView

时间:2012-03-04 00:10:36

标签: ios keyboard scroll textview

在我的应用程序中,我有一个UITextView位于屏幕的底部。所以我所做的是以下代码,但问题是,只有在我点击UITextView的文本位于键盘下方时,它才会正常滚动到键盘上方。

以下是我注册NSNotifications的方法: (在ViewDidLoad中)

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardWasShown:)
                                             name:UIKeyboardDidShowNotification object:nil];

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardWasHidden:)
                                             name:UIKeyboardWillHideNotification object:nil];

方法:

-(void)keyboardWasShown:(NSNotification*)aNotification {
    NSDictionary *info = [aNotification userInfo];

    // Get the size of the keyboard.
    NSValue *aValue = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
    keyboardSize = [aValue CGRectValue].size;

    // Resize the scroll view (which is the root view of the window)
    CGRect viewFrame = [textView frame];

    viewFrame.size.height -= keyboardSize.height;

    textView.frame = viewFrame;

    // Scroll the active text field into view.
    //CGRect textFieldRect = [activeField frame];
    [textView scrollRectToVisible:viewFrame animated:YES];
}

-(void)keyboardWasHidden:(NSNotification*)aNotification {
    // Reset the height of the scroll view to its original value
    CGRect viewFrame = [textView frame];
    viewFrame.size.height += keyboardSize.height;
    textView.frame = viewFrame;
}

我如何取消注册NSNotifications: 在ViewDidUnload中:

[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];

有人看错了什么吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

这是我用来移动textview的代码,所以当KB显示时我可以看到它。我的观点已经在滚动视图中了。

-(void)textViewDidBeginEditing:(UITextView *)textView { //Keyboard becomes visible

    //perform actions.
    NSLog(@"IN VIEW");
    [self scrollTheViewToTop:self.scroller forTheTextView:textView];
}
- (void)textViewDidEndEditing:(UITextView *)textView {
    [self.scroller setContentOffset:CGPointZero animated:YES];
}
- (void)scrollTheViewToTop:(UIScrollView *)scrollView forTheTextView:(UITextView *)textView {

    //Scroll the ScrollView Up tp show the Continue button in the bottom is visible.

    CGPoint pt;
    CGRect rc = [textView bounds];
    rc = [textView convertRect:rc toView:scrollView];
    pt = rc.origin;
    pt.x = 0;
    pt.y -= 60;
    [scrollView setContentOffset:pt animated:YES];
}