Thursday, 12 September 2013

How to calculate the frame of a modal view on iPad?

How to calculate the frame of a modal view on iPad?

When a user taps a UITextField, the keyboard will come up. I scroll up the
UITextField to sit just above the keyboard. This is working fine on
iPhone:

- (void) someWhere
{
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(onKeyboardShow:)
name:UIKeyboardWillShowNotification
object:nil];
}
- (void) onKeyboardShow:(NSNotification *)notification
{
CGRect keyboardRect = [[[notification userInfo]
objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue
];
if (keyboardRect.size.height >= IPAD_KEYBOARD_PORTRAIT_HEIGHT) {
self.containerView.y = self.containerView.y -
keyboardRect.size.width;
} else {
self.containerView.y = self.containerView.y -
keyboardRect.size.height;
}
}
However, it is broken on iPad. On iPad, modal view controllers can be
presented as a sheet that takes up only a portion of the screen. You can
see that there is a gap between the last UITextField and the keyboard on
iPad.

UINavigationController* nav = [[UINavigationController alloc]
initWithRootViewController:someRootViewController];
nav.modalPresentationStyle = UIModalPresentationFormSheet;
[self presentViewController:nav animated:YES completion:nil];
I need to detect the offset of the modal view from the bottom of the
screen and add that to the Y coordinate of the UITextField. This will make
the UITextField flush with the top of the keyboard. I attempted to get the
frame of the modal view by doing this:
- (void) viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
// describe is a category function on UIView that prints out the frame
[self.viewController.view.superview.superview.superview.superview
describe];
}
I did indeed get the frame:
x: 114.000000,
y: 192.000000,
w: 540.000000,
h: 620.000000
But as you can see from my code, it is extremely fragile. Since the view
hierarchy of modal view controllers on iPad is not documented, I had to
reverse engineer the hierarchy by slower traversing up the tree to see
which would be the right one. Is there are less fragile way to get the
frame that I actually care about?

No comments:

Post a Comment