Search code examples
iosuiscrollviewuitextviewuikeyboarduipopover

UITextView inside a UIScrollView inside a Popover is not fully visible when keyboard is displayed


I have a UIPopover with a UIScrollViewinside it that contains a UITextView at the bottom. When the keyboard shows, the popover is resized as the text view begins to be edited. I want the code below to ensure the text view is visible:

- (void)textViewDidBeginEditing:(UITextView *)textView {

    CGRect visRect = textView.frame;
    [self.scrollView scrollRectToVisible:visRect animated:NO];

}

The problem is that the code does not make the entire text view visible. Instead, only the text view up to the bottom of the cursor is shown, as shown below:

enter image description here

How can I show the entire text view/ scroll the scrollview to the bottom? I have tried this:

CGPoint bottomOffset = CGPointMake(0, self.scrollView.contentSize.height - self.scrollView.bounds.size.height);
[self.scrollView setContentOffset:bottomOffset animated:YES];

as explained in this answer but nothing works.

In addition, my scrollview is scrolled to the position shown AFTER the keyboard is moved into place. Ideally I'd like the scrolling to happen before or during the keyboard movement.

Any help would be great.


Solution

  • I found the solution:

    - (void)keyboardDidShow:(NSNotification *)notification {
    NSLog(@"Notification: %s", __PRETTY_FUNCTION__ );
    //
    CGFloat textviewBottom = CGRectGetMaxY(self.commentsTextView.frame);
    CGRect belowTextViewRect = CGRectMake(0, textviewBottom, 350.f, self.scrollView.contentSize.height - textviewBottom);
    // NB! This works ONLY: 1) keyboardDidShow 2) Non-animated;
    // Does NOT work: 1) animated, 2) keyboardWillShow, 3) textViewDidBeginEditing
    [self.scrollView scrollRectToVisible:belowTextViewRect animated:NO];
    }