Keyboard appears in wrong orientation in ios

前提是你 提交于 2019-12-02 02:25:21

I got exactly the same wrong keyboard orientation in some of my view controllers recently after I dropped support for iOS 8 and bumped up the deployment target to iOS 9. It turns out that one of my former colleagues used a solution here to solve an old problem when the base SDK was iOS 9 (we're now in 10, and 11 when coding from Xcode 9 beta). That solution (basically override UIAlertController's supportedInterfaceOrientations to only allow portrait) would force present the keyboard in portrait with newer SDK + deployment target even though the app window and the alert itself are in landscape.

Removing that override solved the problem and I don't see any issue with alert over alert.

Try by adding below code to your viewcontroller's viewDidAppear method

 - (void)viewDidAppear:(BOOL)animated
    {
        [super viewDidAppear:animated];
        [[UIDevice currentDevice] setValue:@(UIDeviceOrientationLandscapeLeft) forKey:@"orientation"];
        [[UIDevice currentDevice] setValue:@(self.interfaceOrientation) forKey:@"orientation"];

    }

Ok, fixed it, my fault I guess.

It seems Keyboard and UIViewController call supportedInterfaceOrientations separately and rotate based on its return value. I had an if-else statement in there and was returning AllButUpsideDown only in some cases. When keyboard checked whether it was supposed to rotate method returned Portrait, and for viewcontroller value was AllButUpsideDown.

So I changed this:

public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations()
    {
        if (someStatement)
        {
            return UIInterfaceOrientationMask.AllButUpsideDown;
        }
        return UIInterfaceOrientationMask.Portrait;
    }

To this:

    public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations()
    {
        return UIInterfaceOrientationMask.AllButUpsideDown;
    }

And now only ShouldAutoRotate decides whether it rotation should happen or not.

To some up it should look like this:

public override bool ShouldAutorotate()
    {
        if (someStatement)
        {
            return true;
        }
        return false;
    }

    public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations()
    {
        return UIInterfaceOrientationMask.AllButUpsideDown;
    }

Create subclass of UIAlertController

MyAlertController.h //header file
@interface MyAlertController : UIAlertController

@end

MyAlertController.m
@implementation MyAlertController 

- (BOOL)shouldAutorotate
{
  return NO;
}

-(UIInterfaceOrientationMask)supportedInterfaceOrientations
{
  [super supportedInterfaceOrientations];    
  return UIInterfaceOrientationMaskLandscape;
}
@end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!