如何根据开关按钮打开和关闭来更改设备的方向?

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

我需要在应用处于 运行 时更改应用方向。我的过程是,如果我打开开关,应用程序应该改变它的方向(即)(i)如果应用程序 运行 横向,然后如果我打开 "ON" 开关按钮然后设备方向应该自动切换为纵向模式.. (ii) 如果应用程序 运行 处于纵向模式,如果我关闭开关,则设备方向应自动切换为横向模式...我已经尝试过一些但它并没有唤醒我..有人可以为此提供一些解决方案吗..

 - (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];
}}

试试下面的代码:

- (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];
        }
}

根据您的要求对 UIInterfaceOrientation 进行修改。