Convert UIKeyboardFrameEndUserInfoKey to View or Window Coordinates

前端 未结 3 2210
灰色年华
灰色年华 2020-12-14 01:15

For the constant UIKeyboardFrameEndUserInfoKey, in the Apple docs it says:

These coordinates do not take into account any rotation facto

3条回答
  •  眼角桃花
    2020-12-14 01:53

    I tried the accepted answer and found that it does not actually provide the CGRect of the keyboard within the view. I found that I have to convert the CGRect from the UIScreen object to the UIWindow object, and from the UIWindow object to the UIView object:

    NSValue * keyboardEndFrame;
    CGRect    screenRect;
    CGRect    windowRect;
    CGRect    viewRect;
    
    // determine's keyboard height
    screenRect    = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    windowRect    = [self.view.window convertRect:screenRect fromWindow:nil];
    viewRect      = [self.view        convertRect:windowRect fromView:nil];
    

    I use the above to resize the root view to not be hidden by the keyboard:

    NSTimeInterval  duration;
    CGRect          frame;
    
    // determine length of animation
    duration  = [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    // resize the view
    frame              = self.view.frame;
    frame.size.height -= viewRect.size.height;
    
    // animate view resize with the keyboard movement
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:duration];
    self.view.frame = frame;
    [UIView commitAnimations];
    

提交回复
热议问题