Prevent AlertView from auto rotating

2020-04-11 08:30发布

问题:

The launch page of my app is set to portrait only with this little bit of code:

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait ;
}

When the app launches a UIAlertView appears for username and password entry. The method to display it is called from viewWillAppear.

This worked fine for iOS6 but since iOS7, if I switch the device to landscape, the main view remains in portrait but the the alert view and keyboard rotate to landscape. A further bizarre quirk is that when I switch back to portrait, only the keyboard switches back (in truncated form), leaving the alert frozen in landscape mode:

Can anyone tell me how to prevent this?

-EDIT-

The autorotate code is called in a separate category:

@implementation UINavigationController (Orientation)

-(NSUInteger)supportedInterfaceOrientations
{
    return [self.topViewController supportedInterfaceOrientations];
}

-(BOOL)shouldAutorotate
{
    if (UIInterfaceOrientationIsLandscape([[UIDevice currentDevice] orientation])) return NO;
    else return YES;
}

@end

-EDIT 2-

I've also tried creating a Category on UIAlertView but it's never called:

@implementation UIAlertView (Orientation)

-(NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

-(BOOL)shouldAutorotate
{
    return NO;
}

-EDIT 3-

I'm not sure how relevant this is but here's the code for showing the alert:

- (void)alertWithMessage:(NSString *)theMessage
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Login"
                                                    message:theMessage
                                                   delegate:self
                                          cancelButtonTitle:@"Login"
                                          otherButtonTitles: nil];

    [alert setAlertViewStyle:UIAlertViewStyleLoginAndPasswordInput];
    UITextField *nameField = [alert textFieldAtIndex:0];
    [alert show];
}

回答1:

Try doing this in viewDidAppear:. I've seen weird behavior like this before because view layouts are not entirely defined yet. In viewDidAppear:, everything is set and laid out, so there shouldn't be any problems at that point.



回答2:

Have you try with implementing shouldAutorotate ? You can do in your case :

- (BOOL)shouldAutorotate
{
    if (UIInterfaceOrientationIsLandscape([[UIDevice currentDevice] orientation])) return NO;
    else return YES;
}


回答3:

I was experiencing this, but the alert was being shown from the AppDelegate. After reading Scott Berrevoet's answer about view layouts not being entirely defined yet I added a very slight delay before showing the alert dialog to give everything some time to set up and that fixed the problem.

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^(void) {
    [self.updateAlert show];
});