Detecting iOS orientation change instantly

后端 未结 6 2120
忘掉有多难
忘掉有多难 2020-12-02 05:38

I have a game in which the orientation of the device affects the state of the game. The user must quickly switch between Landscape, Portrait, and Reverse Landscape orientati

6条回答
  •  一整个雨季
    2020-12-02 06:39

    Add a notifier in the viewWillAppear function

    -(void)viewWillAppear:(BOOL)animated{
      [super viewWillAppear:animated];
      [[NSNotificationCenter defaultCenter] addObserver:self  selector:@selector(orientationChanged:)    name:UIDeviceOrientationDidChangeNotification  object:nil];
    }
    

    The orientation change notifies this function

    - (void)orientationChanged:(NSNotification *)notification{
       [self adjustViewsForOrientation:[[UIApplication sharedApplication] statusBarOrientation]];
    }
    

    which in-turn calls this function where the moviePlayerController frame is orientation is handled

    - (void) adjustViewsForOrientation:(UIInterfaceOrientation) orientation {
    
        switch (orientation)
        {
            case UIInterfaceOrientationPortrait:
            case UIInterfaceOrientationPortraitUpsideDown:
            { 
            //load the portrait view    
            }
    
                break;
            case UIInterfaceOrientationLandscapeLeft:
            case UIInterfaceOrientationLandscapeRight:
            {
            //load the landscape view 
            }
                break;
            case UIInterfaceOrientationUnknown:break;
        }
    }
    

    in viewDidDisappear remove the notification

    -(void)viewDidDisappear:(BOOL)animated{
       [super viewDidDisappear:animated];
       [[NSNotificationCenter defaultCenter]removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
    }
    

    I guess this is the fastest u can have changed the view as per orientation

提交回复
热议问题