如何在不旋转设备的情况下单击按钮更改设备方向

How can i change the device orientation on button click without rotating the device

我想在不旋转设备的情况下更改按钮单击时的设备方向。

这是我的代码:

-(void)funcLandscapeBtnTapped:(UIButton *)button
{ 
      [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeLeft animated:NO];
}

提前致谢。

试试这个代码,它的工作,

您的按钮操作:

isEnablePortraidMode = true;
NSNumber *number = [NSNumber numberWithInt:UIDeviceOrientationLandscapeLeft];
NSNumber *StatusBarOrientation = [NSNumber numberWithInt:UIInterfaceOrientationMaskLandscapeLeft];
[UIViewController attemptRotationToDeviceOrientation];
[[UIDevice currentDevice] setValue:number forKey:@"orientation"];
[[UIApplication sharedApplication] performSelector:@selector(setStatusBarOrientation:) withObject:StatusBarOrientation];
[UIViewController attemptRotationToDeviceOrientation];

并在 Appdelegate 中添加此方法

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
    if(isEnablePortraidMode)
    {
        return UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscape;
     }
    else
    {
         return UIInterfaceOrientationMaskPortrait;
    }
}

试试这个

AppDelegate.h

@property BOOL restrictRotation;

AppDelegate.m

#define APPDELEGATE ((AppDelegate*)[[UIApplication sharedApplication] delegate])

- (UIInterfaceOrientationMask )application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {

    if (self.restrictRotation == YES) {
        return UIInterfaceOrientationMaskLandscape;        
    }
    else {
        if (isiPhone || isiPod) {
            return UIInterfaceOrientationMaskPortrait;
        }else{
            return UIInterfaceOrientationMaskLandscape;
        }
    }
}

YourViewController.m

-(void)funcLandscapeBtnTapped:(UIButton *)button
{
    APPDELEGATE.restrictRotation = YES;
        [[UIDevice currentDevice] setValue:
         [NSNumber numberWithInteger: UIInterfaceOrientationLandscapeRight]
                                    forKey:@"orientation"];
        [self shouldAutorotate];
}
- (BOOL)shouldAutorotate {
    UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
    if ( orientation == UIInterfaceOrientationLandscapeRight
        | orientation == UIInterfaceOrientationLandscapeLeft)
    {
        return NO;
    }

    return YES;
}