Reducing the height of UITextView when Keyboard Shows Up

by Kishore on August 14, 2011

I am working on the iPad version of Kish Multi Pro and I came up with a situation where when I need to edit a post or write a new post, the keyboard pop up, but I am unable to write or edit the text below the keyboard.

How to handle this situation ?

We should use the Keyboard Events to handle this. I am not sure, if I am doing the best way, but it’s working well for me.

In the viewDidLoad, I register the keyboard Events

//Keyboard Events
    // Register for the events
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (keyboardDidShow:)name: UIKeyboardDidShowNotification object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (keyboardDidHide:) name: UIKeyboardDidHideNotification object:nil];

Then we need to takecare of the keyboardDidShow and keyBoardDidHide

-(void) keyboardDidShow: (NSNotification *)notif {
    NSDictionary *userInfo = [notif userInfo];
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
    CGFloat keyboardTop = keyboardRect.origin.y;
    txtPostContentHeight=self.txtPostContent.bounds.size.height;
    //NSLog(@"Original height : %f", txtPostContentHeight);
    CGRect frame = self.txtPostContent.frame;
    txtPostContentFrame=frame;
    //NSLog(@"TextFrame Top %f", frame.origin.y);
    frame.size.height = keyboardTop-frame.origin.y;
    self.txtPostContent.frame=frame;
}

-(void) keyboardDidHide: (NSNotification *)notif {
    NSDictionary *userInfo = [notif userInfo];
    CGRect frame = self.txtPostContent.frame;
    frame.size.height=txtPostContentHeight;
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];

    // Animate the resize of the text view's frame in sync with the keyboard's appearance.
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];

    self.txtPostContent.frame=frame;

    [UIView commitAnimations];
}

There are many other ways, but this worked well for me

  1. Shapewriter Keyboard – Best Keyboard for Handheld devices : I came across an excellent keyboard...
  2. How to get the first image URL from NSString ? : I am working on a RSS...
  3. Loading Custom Nib Files on Start Up : Like every application in iOS, we...
  4. Better Keyboard for Android Phones – ThickButtons : Every PDA user will agree that...
  5. Reducing Bounce Rate of your blog : Bounce rate is expressed in percentage...