How to force view controller orientation in iOS 8?

前端 未结 25 2554
太阳男子
太阳男子 2020-11-22 13:11

Before iOS 8, we used below code in conjunction with supportedInterfaceOrientations and shouldAutoRotate delegate methods to force app orie

25条回答
  •  佛祖请我去吃肉
    2020-11-22 13:30

    It looks like even thou here is so much answers no one was sufficient for me. I wanted to force orientation and then on going back go back to device orientation but [UIViewController attemptRotationToDeviceOrientation]; just did'nt work. What also did complicated whole thing is that I added shouldAutorotate to false based on some answer and could not get desired effects to rotate back correctly in all scenarios.

    So this is what I did:

    Before pushing of controller in call in his init constructor this:

    _userOrientation = UIDevice.currentDevice.orientation;
    [UIDevice.currentDevice setValue:@(UIInterfaceOrientationPortrait) forKey:@"orientation"];
    [self addNotificationCenterObserver:@selector(rotated:)
                                   name:UIDeviceOrientationDidChangeNotification];
    

    So I save last device orientation and register for orientation change event. Orientation change event is simple:

    - (void)rotated:(NSNotification*)notification {
        _userOrientation = UIDevice.currentDevice.orientation;
    }
    

    And on view dissmising I just force back to any orientation I have as userOreintation:

    - (void)onViewDismissing {
        super.onViewDismissing;
        [UIDevice.currentDevice setValue:@(_userOrientation) forKey:@"orientation"];
        [UIViewController attemptRotationToDeviceOrientation];
    }
    

    And this has to be there too:

    - (BOOL)shouldAutorotate {
        return true;
    }
    
    - (UIInterfaceOrientationMask)supportedInterfaceOrientations {
        return UIInterfaceOrientationMaskPortrait;
    }
    

    And also navigation controller has to delegate to shouldAutorotate and supportedInterfaceOrientations, but that most people already have I believe.

    PS: Sorry I use some extensions and base classes but names are quite meaningful so concept is understandable, will make even more extensions because it's not too much pretty now.

提交回复
热议问题