iOS 横屏的问题,相信很多新手朋友都是懵懵懂懂

来源:互联网 发布:淘宝店铺绑定旺旺 编辑:程序博客网 时间:2024/05/01 19:49



关于iOS 横屏的问题,相信很多 新手朋友都是懵懵懂懂的,什么需要ios6以上啊,ios8之类的,或者,都实现了,网上个个大神的代码。但是!


自己的需求跟他们写的对不上,还得一脸懵逼。! 好!今天,我就教大家一个 简单的方法。来解决 横屏的问题,大家想怎么转,想怎么变!。想那个控制器转,就哪个控制器转,想什么时候横屏!就什么时候横屏!就是这么任性

话不多说,开始!我一步步的教你怎么搞!



首先! 第一步。Appdelegate.h

             在你的Appdelegate.h文件中,定义一个变量

       @property(nonatomic,assign)NSInteger allowRotation; 这个变量就是控制你是否允许旋转的。开关,然后在Appdelegate.m 看清楚,是.m文件中实现这个方法!!


这个地方你也可以定义一个宏,方便调用


#define ApplicationDelegate ((AppDelegate *)[UIApplication sharedApplication].delegate)



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

    if (self.allowRotation) {

        returnUIInterfaceOrientationMaskLandscape;

    }

    returnUIInterfaceOrientationMaskPortrait;

}


看清楚!不会写,总会粘贴吧!这个,地方,我解释下。默认是返回正常的屏幕。当你allowrotation返回YES,就会变成横屏!,这出,你需要哪个方向,就写方向。这个地方你写了两个,那么,就有这两个方向是可以旋转的,注意!!,是可以旋转,不是强制旋转。意思就是,你得通过重力感应,说白了,就是转动手机,如果允许这两个方向,就会转动。


第二步   自定义一个NavigationController ,最好作为base,然后,在这个nav中,实现如下方法

- (BOOL)shouldAutorotate{

    

    returnApplicationDelegate.allowRotation;

}



- (UIInterfaceOrientationMask)supportedInterfaceOrientations

{

    returnUIInterfaceOrientationMaskPortrait;

}


- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation

{

    returnUIInterfaceOrientationPortrait;

}



此处,!你只需要拷贝就行!!意思就是 默认是正常的竖屏!



然后!!!!!就是使用了!


如果你想,摸个控制器,是横屏,只需要,

ApplicationDelegate.allowRotation =YES;

然后,一切都美好了,!就完成了你的需求,perfect!


或者,你的需求是,点击某个全屏按钮后,会变成 横屏!然后你就说,你也是个骗子,需求实现不了!!


砖友兄弟,别着急!继续往下看!!



你只需要把如下代码拷贝到你的点击方法里!!




- (void)forceOrientation: (UIInterfaceOrientation)orientation {

    if ([[UIDevicecurrentDevice] respondsToSelector:@selector(setOrientation:)]) {

        SEL selector =NSSelectorFromString(@"setOrientation:");

        NSInvocation *invocation = [NSInvocationinvocationWithMethodSignature:[UIDeviceinstanceMethodSignatureForSelector:selector]];

        [invocation setSelector:selector];

        [invocation setTarget: [UIDevicecurrentDevice]];

        int val = orientation;

        [invocation setArgument:&valatIndex:2];

        [invocation invoke];

    }

}



调用方法如下!!,想要哪个方向,!就强制转哪个方向!!!!!!


[selfforceOrientation:UIInterfaceOrientationLandscapeRight];






0 0
原创粉丝点击