Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIModalPresentationFormSheet on iPad. How to adjust UITextView height when keyboard appears

Tags:

ios

keyboard

ipad

UITextView is subview of the modal controller view. I need to decrease UITextView height when keyboard appears in order to bottom border y coordinate of the UITextView to be equal to keyboard's top y coordinate. I'getting keyboard height

CGRect frameBegin = [[notification.userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue] ;
CGRect frameEnd = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];

CGRect resultBegin = [self.view convertRect:frameBegin fromView:nil];
CGRect resultEnd = [self.view convertRect:frameEnd fromView:nil];

CGFloat kbdHeight = resultBegin.origin.y  - resultEnd.origin.y;

The problem is that this modal view jumps up when keyboard appears. How to calculate keyboard's top border coordinate in this case?

like image 345
Michael Avatar asked Feb 09 '13 10:02

Michael


Video Answer


1 Answers

You could do this:

1. Register for keyboard notifications:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(myTextViewHeightAdjustMethod:)
                                             name:UIKeyboardWillShowNotification
                                           object:nil];

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(myTextViewHeightAdjustMethod:)
                                             name:UIKeyboardDidShowNotification
                                           object:nil];

2. Calculate intersection and adjust textView height with the bottom constraint

    - (void)myTextViewHeightAdjustMethod:(NSNotification *)notification
    {
        NSDictionary *userInfo = [notification userInfo];
        CGRect keyboardFinalFrame = [[userInfo emf_ObjectOrNilForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];

        CGPoint keyboardOriginInView = [self.view convertPoint:keyboardFinalFrame.origin fromView:nil];

             CGFloat intersectionY = CGRectGetMaxY(self.view.frame) - keyboardOriginInView.y;

             if (intersectionY >= 0)
             {
                 self.textViewBottomConstraint.constant = intersectionY + originalTextViewBottomConstraint;

                 [self.textView setNeedsLayout];
    }

Remember to unregister for notifications.

like image 194
Juan Sagasti Avatar answered Oct 13 '22 01:10

Juan Sagasti