Search code examples
iphoneioscocoa-touchios5

How do I create a UITextView that exactly fits above the keyboard?


I want to create a view, like the Facebook or Twitter app's share dialog, for example, where there is just a UITextView and a permanent keyboard. I can see how to start with the keyboard visible from this answer, but I'm not sure how to size the UITextView to fit exactly above the keyboard. If I don't, text can get hidden under the keyboard which is awkward.


Solution

  • I found a helpful code sample in the Apple documentation for this: https://developer.apple.com/library/ios/#samplecode/KeyboardAccessory/Introduction/Intro.html

    Here's the code I ended up with. I'm not worrying about the keyboard hiding, since in my view, the keyboard should never hide.

    - (void)viewWillAppear:(BOOL)flag
    {
        [super viewWillAppear:flag];
    
        // Listen for the keyboard to show up so we can get its height
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    
        // Set focus on the text view to display the keyboard immediately
        [self.textView becomeFirstResponder];
    }
    - (void)keyboardWillShow:(NSNotification *)notification
    {
        /*
         Reduce the size of the text view so that it's not obscured by the keyboard.
         */
    
        NSDictionary *userInfo = [notification userInfo];
    
        // Get the origin of the keyboard when it's displayed.
        NSValue* keyboardFrame = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    
        // 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 = [keyboardFrame CGRectValue];
        keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
    
        // Set the text view's frame height as the distance from the top of the view bounds
        // to the top of the keyboard
        CGFloat keyboardTop = keyboardRect.origin.y;
        CGRect newTextViewFrame = self.view.bounds;
        newTextViewFrame.size.height = keyboardTop - self.view.bounds.origin.y;
        self.textView.frame = newTextViewFrame;
    }