我有一个视图控制器用UITextView显示一个视图,我想在键盘出现时调整视图的大小,以便UITextView不被键盘覆盖。我几乎在所有情况下都能正常工作。据我所知,只有当视图控制器在ModalPresentationStyleFormSheet中呈现,并且仅在LandscapeRight方向呈现时,我仍然在iPad上看到一些奇怪的现象。如何找到未被键盘覆盖的部分视图(UIModalPresenationStyleFormSheet)?
我的视图控制器的-keyboardWillShow的相关部分:
// We'll store my frame above the keyboard in availableFrame
CGRect availableFrame = self.view.frame;
// Find the keyboard size
NSDictionary *userInfo = [notification userInfo];
NSValue keyboardFrameScreenValue = userInfo[UIKeyboardFrameBeginUserInfoKey];
CGRect keyboardFrameScreen = [keyboardFrameScreenValue CGRectValue];
CGRect keyboardFrame = [self.view convertRect:keyboardFrameScreen fromView:nil];
CGSize keyboardSize = keyboardFrame.size;
// Figure out how much of my frame is covered by the keyboard
CGRect screenBounds = [self.view convertRect:[UIScreen mainScreen].bounds
fromView:nil];
CGRect myBoundsScreen = [self.view boundsInWindow]; // See below
CGFloat myBottom = myBoundsScreen.origin.y + myBoundsScreen.size.height;
CGFloat keyboardTop = screenBounds.size.height - keyboardSize.height;
CGFloat lostHeight = myBottom - keyboardTop;
availableFrame.size.height -= lostHeight;
- [UIView的boundsInWindow]:
- (CGRect)boundsInWindow {
UIInterfaceOrientation orientation =
[UIApplication sharedApplication].statusBarOrientation;
CGRect bounds = [self convertRect:self.bounds toView:self.window];
if (UIInterfaceOrientationIsLandscape(orientation)) {
// Swap origin
CGFloat x = bounds.origin.y;
bounds.origin.y = bounds.origin.x;
bounds.origin.x = x;
// Swap size
CGFloat width = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = width;
}
return bounds;
}
这工作,大部分时间。当我的应用程序处于面向用户界面的LandscapeRight时,我从--boundsInWindow得到的原点比它应该低很多。什么可能导致这个?
感谢您的帮助!
这对我很好。我发现的唯一的错误是对于UIInterfaceOrientationLandscapeLeft或UIInterfaceOrientationLandscapeRight,您仍然应该使用'keyboardSize.height',而不是'keyboardSize.width'。 (在iOS 7.0 iPad模拟器上测试) –
出于某种原因,设置contentInsets看起来没有任何作用。你有一些示例代码显示这个片段的工作? – fatuhoku
@RizwanSattar我也需要使用windowBounds.size.height,而不是windowBounds.size.width –