Detecting iOS UIDevice orientation

后端 未结 8 932
一生所求
一生所求 2020-11-28 03:29

I need to detect when the device is in portrait orientation so that I can fire off a special animation. But I do not want my view to autorotate.

How do I override a

8条回答
  •  醉话见心
    2020-11-28 04:15

    If you came to this question looking for how to detect an orientation change (without necessarily wanting to disable the rotation), you should also be aware of viewWillTransitionToSize, which is available from iOS 8.

    Swift example from here

    override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
    
        coordinator.animateAlongsideTransition({ (UIViewControllerTransitionCoordinatorContext) -> Void in
    
            let orient = UIApplication.sharedApplication().statusBarOrientation
    
            switch orient {
            case .Portrait:
                println("Portrait")
                // Do something
            default:
                println("Anything But Portrait")
                // Do something else
            }
    
            }, completion: { (UIViewControllerTransitionCoordinatorContext) -> Void in
                println("rotation completed")
        })
    
        super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
    }
    

    And if you don't need to worry about the actual orientation:

    override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
    
        // do something
    
        super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
    }
    

    Objective-C example from here

    - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id)coordinator
    {   
        [coordinator animateAlongsideTransition:^(id context)
        {
            UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
            // do whatever
        } completion:^(id context)
        { 
    
        }];
    
        [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    }
    

    And if you don't need to worry about the actual orientation (taken from this answer):

    - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id)coordinator
    {
        // Do view manipulation here.
        [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    }
    

    See also

    • iOS 8 Orientation Change Detection
    • iOS8 Day-by-Day :: Day 14 :: Rotation Deprecation

提交回复
热议问题