2012-03-04 76 views
0

在我的应用程序中,我有一个UITextView,它位于屏幕的底部。所以我做的是下面的代码,但问题是,有时如果单击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]; 

有没有人看到任何错误?

谢谢!

+0

如果只是有时不会发生滚动,请检查您的框架计算和移动。它可能会出错。 – cocoakomali 2012-03-04 03:49:13

+0

我应该怎么发布NSLog,因为所有这些值都很混乱。当我发布这些值时,也许别人会看到我的问题。 – 2012-03-04 04:22:54

+0

您应该打印原始视图框架,键盘大小和最终修改后的视图框架。 – cocoakomali 2012-03-09 18:23:39

回答

0

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

-(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]; 
}