1. 程式人生 > >強制橫屏(僅適用於present情景)

強制橫屏(僅適用於present情景)

設定橫屏很簡單,只需要勾選上這兩項就可以了

但這是設定全域性的橫屏允許,很多時候需求是大多介面只允許豎屏,只有某個介面才需要設定橫屏(例如播放視訊介面等),所以這時這兩項就不能勾選上,那要怎麼設定橫屏呢,其實很簡單,當然本文的方法只適用present檢視

首先在appdelegate中新增一個屬性

@property (nonatomic,assign) BOOL allowRotation;

然後新增代理方法

-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow
*)window { if (self.allowRotation) { return UIInterfaceOrientationMaskLandscape; } return UIInterfaceOrientationMaskPortrait; }

在需要設定橫屏的檢視present前設定為YES

AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    delegate.allowRotation = YES;

在橫屏檢視dismiss前設定為NO即可恢復豎屏

隨意轉換橫豎屏(present 視訊播放時全屏轉換)

//修改全域性屬性並呼叫轉屏方法
AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;     
appDelegate.allowRotation = NO;      
[self setNewOrientation:NO];//呼叫轉屏程式碼

//強制轉屏
- (void)setNewOrientation:(BOOL)fullscreen

{
    if (fullscreen) {

        NSNumber
*resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown]; [[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"]; NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];//橫屏方向(根據需求選填) [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"]; }else{ NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown]; [[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"]; NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationPortrait]; [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"]; } }