UIAlertController is moved to buggy position at top of screen when it calls `presentViewController:`

13,756

Solution 1

rdar://19037589 was closed by Apple

Apple Developer Relations | 25-Feb-2015 10:52 AM

There are no plans to address this based on the following:

This isn't supported, please avoid presenting on a UIAlertController.

We are now closing this report.

If you have questions about the resolution, or if this is still a critical issue for you, then please update your bug report with that information.

Please be sure to regularly check new Apple releases for any updates that might affect this issue.

Solution 2

I encountered a situation where sometimes a modal view would present itself on top of a an alert (silly situation, I know), and the UIAlertController could appear in the top left (like the 2nd screenshot of the original question), and I found a one-liner solution that seems to work. For the controller that's about to be presented on the UIAlertController, change its modal presentation style like so:

viewControllerToBePresented.modalPresentationStyle = .OverFullScreen

This should be done just before you call presentViewController(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion completion: (() -> Void)?)

Solution 3

I was having this issue as well. If I presented a view controller while a UIAlertController was presented, the alert would go to the top left.

My fix is to refresh the center of the UIAlertController's view in viewDidLayoutSubviews; achieved by subclassing UIAlertController.

class MyBetterAlertController : UIAlertController {

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        let screenBounds = UIScreen.mainScreen().bounds

        if (preferredStyle == .ActionSheet) {
            self.view.center = CGPointMake(screenBounds.size.width*0.5, screenBounds.size.height - (self.view.frame.size.height*0.5) - 8)
        } else {
            self.view.center = CGPointMake(screenBounds.size.width*0.5, screenBounds.size.height*0.5)
        }
    }
}

Solution 4

That is a bit disappointing... moving alerts to be UIViewControllers, but then disallowing some regular usage of them. I work on an application which did something similar -- it sometimes needs to jump to a new user context, and doing that presented a new view controller over top of whatever was there. Actually having the alerts be view controllers is almost better in this case, as they would be preserved. But we are seeing the same displacement now that we have switched to UIViewControllers.

We may have to come up with a different solution (using different windows perhaps), and maybe we avoid presenting if the top level is a UIAlertController. But, it is possible to restore the correct positioning. It may not be a good idea, because the code could break if Apple ever changes their screen positioning, but the following subclass seems to work (in iOS8) if this functionality is very much needed.

@interface MyAlertController : UIAlertController
@end

@implementation MyAlertController
/*
 * UIAlertControllers (of alert type, and action sheet type on iPhones/iPods) get placed in crazy
 * locations when you present a view controller over them.  This attempts to restore their original placement.
 */
- (void)_my_fixupLayout
{
    if (self.preferredStyle == UIAlertControllerStyleAlert && self.view.window)
    {
        CGRect myRect = self.view.bounds;
        CGRect windowRect = [self.view convertRect:myRect toView:nil];
        if (!CGRectContainsRect(self.view.window.bounds, windowRect) || CGPointEqualToPoint(windowRect.origin, CGPointZero))
        {
            CGPoint center = self.view.window.center;
            CGPoint myCenter = [self.view.superview convertPoint:center fromView:nil];
            self.view.center = myCenter;
        }
    }
    else if (self.preferredStyle == UIAlertControllerStyleActionSheet && self.traitCollection.userInterfaceIdiom == UIUserInterfaceIdiomPhone && self.view.window)
    {
        CGRect myRect = self.view.bounds;
        CGRect windowRect = [self.view convertRect:myRect toView:nil];
        if (!CGRectContainsRect(self.view.window.bounds, windowRect) || CGPointEqualToPoint(windowRect.origin, CGPointZero))
        {
            UIScreen *screen = self.view.window.screen;
            CGFloat borderPadding = ((screen.nativeBounds.size.width / screen.nativeScale) - myRect.size.width) / 2.0f;
            CGRect myFrame = self.view.frame;
            CGRect superBounds = self.view.superview.bounds;
            myFrame.origin.x = CGRectGetMidX(superBounds) - myFrame.size.width / 2;
            myFrame.origin.y = superBounds.size.height - myFrame.size.height - borderPadding;
            self.view.frame = myFrame;
        }
    }
}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    [self _my_fixupLayout];
}

@end

Apple may consider the view positioning to be private, so restoring it in this way may not be the best idea, but it works for now. It might be possible to store off the old frame in an override of -presentViewController:animated:, and simply restore that instead of re-calculating.

It's possible to swizzle UIAlertController itself to do the equivalent of the above, which would also cover UIAlertControllers presented by code you don't control, but I prefer to only use swizzles in places where it's a bug that Apple is going to fix (thus there is a time when the swizzle can be removed, and we allow existing code to "just work" without mucking it up just for a bug workaround). But if it's something that Apple is not going to fix (indicated by their reply as noted in another answer here), then it's usually safer to have a separate class to modify behavior, so you are using it only in known circumstances.

Solution 5

I think that you only should to categorize UIAlertController like this:

@implementation UIAlertController(UIAlertControllerExtended)

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    if (self.preferredStyle == UIAlertControllerStyleAlert) {
        __weak UIAlertController *pSelf = self;

        dispatch_async(dispatch_get_main_queue(), ^{
            CGRect screenRect = [[UIScreen mainScreen] bounds];
            CGFloat screenWidth = screenRect.size.width;
            CGFloat screenHeight = screenRect.size.height;

            [pSelf.view setCenter:CGPointMake(screenWidth / 2.0, screenHeight / 2.0)];
            [pSelf.view setNeedsDisplay];
        });
    }
}

@end
Share:
13,756

Related videos on Youtube

pkamb
Author by

pkamb

Mac / iOS engineer

Updated on June 06, 2022

Comments

  • pkamb
    pkamb about 2 years

    Presenting a view from a UIAlertController moves the alert to a buggy position at the top-left corner of the screen. iOS 8.1, device and simulator.

    We have noticed this in an app when we attempt to present a view from the current "top-most" view. If a UIAlertController happens to be the top-most view we get this behavior. We have changed our code to simply ignore UIAlertControllers, but I'm posting this in case others hit the same issue (as I couldn't find anything).

    We have isolated this to a simple test project, full code at the bottom of this question.

    1. Implement viewDidAppear: on the View Controller in a new Single View Xcode project.
    2. Present aUIAlertController alert.
    3. Alert controller immediately calls presentViewController:animated:completion: to display and then dismiss another view controller:

    The moment the presentViewController:... animation begins, the UIAlertController is moved to the top-left corner of the screen:

    Alert has moved to top of screen

    When the dismissViewControllerAnimated: animation ends, the alert has been moved even further into the top-left margin of the screen:

    Alert has moved into the top-left margin of the screen

    Full code:

    - (void)viewDidAppear:(BOOL)animated {
        // Display a UIAlertController alert
        NSString *message = @"This UIAlertController will be moved to the top of the screen if it calls `presentViewController:`";
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"UIAlertController iOS 8.1" message:message preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"I think that's a Bug" style:UIAlertActionStyleCancel handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
    
        // The UIAlertController should Present and then Dismiss a view
        UIViewController *viewController = [[UIViewController alloc] init];
        viewController.view.backgroundColor = self.view.tintColor;
        [alert presentViewController:viewController animated:YES completion:^{
            dispatch_after(0, dispatch_get_main_queue(), ^{
                [viewController dismissViewControllerAnimated:YES completion:nil];
            });
        }];
    
        // RESULT:
        // UIAlertController has been moved to the top of the screen.
        // http://i.imgur.com/KtZobuK.png
    }
    

    Is there anything in the above code that would be causing this issue? Do any alternatives exist that would allow bug-free presentation of a view from a UIAlertController?

    rdar://19037589
    http://openradar.appspot.com/19037589

    • Jageen
      Jageen over 9 years
      weird behavior, Thanks for pointing out bug
  • malinois
    malinois over 9 years
    Very good fix ! I have tried this code, I have put this code in a category of UIAlertController, and all system alerts are automatically fixed.
  • pkamb
    pkamb about 9 years
    I will accept a different answer if this is fixed in an iOS update.
  • Carl Lindberg
    Carl Lindberg almost 9 years
    I suspect the use of UIModalPresentationOverFullScreen is the key here, as that should avoid the problem since it would leave the underlying views in the view hierarchy, and avoid the appearance calls on them while another view controller is modally on top of it.
  • Bradley Thomas
    Bradley Thomas over 8 years
    "This isn't supported. Please spend the rest of your life re-working architecture that was previously stable"
  • Carl Lindberg
    Carl Lindberg over 7 years
    If Apple ever adds an actual implementation of -viewDidAppear: on UIAlertController, your implementation will prevent that code from ever being called, if it's not already. You need to do a more careful swizzle if there is an existing implementation.
  • Tritmm
    Tritmm over 7 years
    haha, this answer so simple and clean. it worked for me, thanks you so much!
  • Brian White
    Brian White almost 7 years
    The UIAlertController class is intended to be used as-is and does not support subclassing. The view hierarchy for this class is private and must not be modified. developer.apple.com/documentation/uikit/uialertcontroller#//‌​…
  • mfaani
    mfaani almost 7 years
    @BrianWhite so you're saying this doesn't work. Or that even if it does, it's not reliable and could break...
  • Brian White
    Brian White almost 7 years
    The latter. If it works, it's not officially supported and could break or have unexpected results at any time.
  • charshep
    charshep almost 7 years
    I had a similar requirement as pkamb and ran into the same problem with the alert shifting position. As of iOS 10 the solution for me was to simply set UIModalPresentationOverFullScreen explicitly on the view controller I was presenting. No other code was required.
  • alseether
    alseether about 6 years
    Posting raw code as an answer is discouraged, please, add some explanations about what you did and how your solution works.