Keyboard “WillShow” and “WillHide” vs. Rotation

前端 未结 7 604
青春惊慌失措
青春惊慌失措 2021-01-31 04:56

I\'ve got a view controller listening for both UIKeyboardWillShowNotification and UIKeyboardWillHideNotification. The handlers for these notifications adjust various parts of th

7条回答
  •  误落风尘
    2021-01-31 05:20

    I use the following code to get the size of the keyboard which works fine for all rotations

    NSDictionary *info = [aNotification userInfo];
    if (UIInterfaceOrientationIsLandscape(self.interfaceOrientation))
      kbHeight = [[NSNumber numberWithFloat:[[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size.width] floatValue];
    else
      kbHeight = [[NSNumber numberWithFloat:[[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size.height] floatValue];
    NSLog(@"keyboard height = %F",kbHeight);
    

    I then test for the orientation using the status bar orientation (which works in the first launch case for the iPad) and shift the view in the relative direction needed to make space for the keyboard. This works perfectly, if the keyboard is visible then it relocates to the correct position on rotations.

    UIDeviceOrientation orientation =  [UIApplication sharedApplication].statusBarOrientation;
    
    
    if (orientation == UIDeviceOrientationPortrait)
      {
      NSLog(@"Orientation: portrait");
      self.originalCenter = self.view.center;
      self.view.center = CGPointMake(self.originalCenter.x, self.originalCenter.y-kbHeight);
      }
    
    if (orientation == UIDeviceOrientationPortraitUpsideDown)
      {
      NSLog(@"Orientation: portrait upside down");
      self.originalCenter = self.view.center;
      self.view.center = CGPointMake(self.originalCenter.x, self.originalCenter.y+kbHeight);
      }
    
    if (orientation == UIDeviceOrientationLandscapeLeft)
      {
      NSLog(@"Orientation: landscape left");
      self.originalCenter = self.view.center;
      self.view.center = CGPointMake(self.originalCenter.x+kbHeight,self.originalCenter.y);
      }
    
    if (orientation == UIDeviceOrientationLandscapeRight)
      {
      NSLog(@"Orientation: landscape right");
      self.originalCenter = self.view.center;
      self.view.center = CGPointMake(self.originalCenter.x-kbHeight,self.originalCenter.y);
      }
    

    You can return the view to its original position when the keyboard disappears or via a textFileDidEndEditing function.

提交回复
热议问题