Search code examples
iosobjective-cuiinterfaceorientation

How to change the orientation of an device depending upon switch button ON & OFF?


I need to change the app orientation while app is running. My process is , if i turn ON the switch, app should change its orientation (i.e) (i) if app running in landscape orientation, then if i turn "ON" the switch button then the device orientation should automatically change towards portrait mode.. (ii) if app running in Portrait mode, if i turn OFF the switch then the device orientation should automatically change towards landscape mode... i have tried something but it is not woking for me.. could any one please give some solution for this..

 - (IBAction)PortraitSwitchPressed:(UISwitch *)sender
   {
     if (sender.isOn)
     {
        UIInterfaceOrientationMaskPortrait;
        [[UIDevice currentDevice]setOrientation:UIInterfaceOrientationPortrait]; // no visible @interface for 'UIDevice' declares the selector setorientation
          [self.PortraitSwitch setOn:YES animated:YES];
      }
else
     {

       UIInterfaceOrientationMaskLandscape;
      [[UIDevice currentDevice] setOrientation:UIInterfaceOrientationMaskLandscape];
         [self.PortraitSwitch setOn:NO animated:YES];
}}

Solution

  • Try below code:

    - (IBAction)PortraitSwitchPressed:(UISwitch *)sender
    {
            if (sender.isOn)
            {
                NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
                [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
                [self.PortraitSwitch setOn:YES animated:YES];
            }
            else
            {
    
                NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];//or UIInterfaceOrientationLandscapeRight
                [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
                [self.PortraitSwitch setOn:NO animated:YES];
            }
    }
    

    Do modification for UIInterfaceOrientation as per your requirement.