@selector的objc_msgSend(setOrientation :)

时间:2014-10-14 08:56:29

标签: ios

在我的应用程序中,我使用objc_msgSend来更改整个设备的方向。在应用程序中有2个按钮(横向和纵向)。每当用户点击Landscape时,App就应该是landscape.Similar for Portrait。

但这种方法并不是每次都改变方向。有时它可以工作,有时不工作。

代码是: -

- (void)updateOrientation
{
    NSInteger mode = -1;
    switch (appDel.orientationMode)
    {
        case 2:
        {
            UIDeviceOrientation orientation =  (UIDeviceOrientation)[UIApplication sharedApplication].statusBarOrientation;
            if (orientation == UIDeviceOrientationLandscapeLeft ||
                    orientation == UIDeviceOrientationLandscapeRight
                    || orientation == 0)
            {
                // do nothing
            }
            else if(orientation == UIDeviceOrientationPortrait) {

                mode = UIInterfaceOrientationLandscapeRight ;
            }
            else if (orientation == UIDeviceOrientationPortraitUpsideDown ) {
                mode = UIInterfaceOrientationLandscapeLeft;
            }
        }
            break;
        case 3:
        {
            UIDeviceOrientation orientation =  (UIDeviceOrientation)[UIApplication sharedApplication].statusBarOrientation;

            if (orientation == UIDeviceOrientationPortrait ||
                orientation == UIDeviceOrientationPortraitUpsideDown
                || orientation == 0)
            {
                // do nothing
            }
            else if (orientation == UIDeviceOrientationLandscapeRight) {

                mode = UIInterfaceOrientationPortraitUpsideDown ;
            }
            else if (orientation == UIDeviceOrientationLandscapeLeft) {

                 mode = UIInterfaceOrientationPortrait ;
            }
        }
            break;
    }

    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)] && (mode != -1))
    {
        objc_msgSend([UIDevice currentDevice], @selector(setOrientation:), mode);
    }
}

1 个答案:

答案 0 :(得分:0)

更改方向时尝试使用此代码

NSNumber *value = [NSNumber numberWithInt:YourDesiredOrientation];
[[UIDevice currentDevice] setValue:value forKey:@"orientation"];