我有一個視圖控制器用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 –