Search code examples
objective-cipadios7modalviewcontrolleruimodalpresentationstyle

Popover with ModalPresentationStyle is not centered in iOS 7 iPad


I have a problem with iOS 7 that seems to be a bug or I just don't do something right. I have modalViewController that appears as a popover on iPad with ModalPresentationStyle. And it is not standard size, custom sized. Here is the code:

myViewController *myVC = [[myViewController alloc] init];
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:myVC];
[nav setModalPresentationStyle:UIModalPresentationFormSheet];
[nav setModalTransitionStyle: UIModalTransitionStyleFlipHorizontal];
[self presentViewController:nav animated:YES completion:nil];
nav.view.superview.bounds = CGRectMake(0, 0, 320, 465);

It's all working fine in iOS 6, but in iOS 7 it's not centered. But if I set ModalTransitionStyle to UIModalTransitionStyleCrossDissolve it works fine. But only in this mode. Maybe someone stumbled on this one too and know how to fix it? I'm not a big fan of dissolve effect. Thank you.


Solution

  • I have a method where the old custom modal presentation style fromsheet works with iOS <=7 although you might set custom height and width.

    Keep in mind that this method might not work in any newer version in the future

    - (void) hackModalSheetSize:(CGSize) aSize ofVC:(UIViewController *) aController;
    {
    
        void (^formSheetBlock) (void) = ^{
            int preferredWidth = aSize.width;
            int preferredHeight = aSize.height;
    
            CGRect frame = CGRectMake((int) 1024/2 - preferredWidth/2,
                                      (int) 768/2 - preferredHeight/2,
                                      preferredWidth, preferredHeight);
            aController.view.superview.frame = frame;
            if([aController respondsToSelector:@selector(edgesForExtendedLayout)]) { //ios7
                aController.view.superview.backgroundColor = [UIColor clearColor];
            } else { // < ios7
                UIImageView *backgroundView = [aController.view.superview.subviews objectAtIndex:0];
                [backgroundView removeFromSuperview];
            }
        };
    
        //on ios < 7 the animation would be not as smooth as on the older versions so do it immediately
        if(![self respondsToSelector:@selector(edgesForExtendedLayout)]) {
            formSheetBlock();
            return;
        }
    
        double delayInSeconds = .05;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            formSheetBlock();
        });
    }