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

时间:2017-12-23 06:51:06

标签: ios objective-c iphone iphone-developer-program iosdeployment

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

这是我的代码:

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

提前致谢。

2 个答案:

答案 0 :(得分:0)

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

你的按钮动作:

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

答案 1 :(得分:0)

试试这个

<强> 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;
}