Search code examples
ioskeyboarduitextviewnsnotification

iOS - How to reference Keyboard Notification outside of method?


I currently register for keyboardWillBeHidden and keyboardFrameDidChange methods to change the ScrollView size when the keyboard is open.

In my textViewDidChange, I have a little text to make sure that cursor is in the view:

if ([textView.text hasSuffix:@"\n"]) {
     [CATransaction setCompletionBlock:^{[self scrollToCaretInTextView:self.logText animated:NO];}];
 } else {
     [self scrollToCaretInTextView:self.logText animated:NO];}

This references this method:

- (void)scrollToCaretInTextView:(UITextView *)textView animated:(BOOL)animated
{
    CGRect rect = [textView caretRectForPosition:textView.selectedTextRange.end];
    rect.size.height += textView.textContainerInset.bottom;
    [textView scrollRectToVisible:rect animated:animated];
}

How can I reference my notifications in this scrollToCaretInTextView to be able to change the CGRect when the keyboard is up? Now it doesn't recognize when the cursor is underneath the keyboard.

I've tried to go around this, but I need to get that keyboard height and I'm not sure how to apply it to this method since its not an NSNotificaiton.


Solution

    1. Get keyboardWillAppear notification, you can get the animation constants (frames, durations, curves) - use that to set your scrollview insets.

    2. In your notification keyboardDidAppear Notification, thats after your keyboard animation - call the scrollToCaretInTextView method. If you wanted to scroll to the textview, it should be as simple as calling, [scrollView scrollToRectVisible:textview.frame]