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



我需要在应用程序运行时更改应用程序的方向。我的过程是,如果我打开开关,应用程序应该更改其方向(即)(i)如果应用程序以横向运行,那么如果我打开"打开"开关按钮,那么设备方向应该自动更改为纵向模式。。(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进行修改。

最新更新