iOS強制豎屏

以強制豎屏爲例,強制橫屏同理。

如果要全部豎屏,直接在Info.plist中設置即可。這裏討論的是全局可轉屏,但是某些頁面只能豎屏。

要做到強制豎屏,有兩個要點。

1. 禁止轉屏

2. 豎屏進入頁面。

僅僅設置禁止轉屏還不能保證一定是豎屏的。因爲如果從橫屏的狀態進入當前頁面的的話,當前頁面就會也是橫屏的。所以要強制豎屏,除了禁止轉屏,還要做到豎屏進入頁面。


禁止轉屏

禁止轉屏可以通過重寫shouldAutoRotate實現。iOS7中,需要增加UINavigationController的支持。

具體參考iOS7中禁止某些頁面轉屏

實現擴展

#import "UINavigationController+Autorotate.h"

@implementation UINavigationController (Autorotate)

-(BOOL)shouldAutorotate {
    return [[self.viewControllers lastObject] shouldAutorotate];
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return [[self.viewControllers lastObject] preferredInterfaceOrientationForPresentation];
}

-(NSUInteger)supportedInterfaceOrientations{
    return [[self.viewControllers lastObject] supportedInterfaceOrientations];
}

-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation{
    return [[self.viewControllers lastObject] shouldAutorotateToInterfaceOrientation:toInterfaceOrientation];
}
@end


豎屏進入頁面

要做到豎屏進入頁面,根據網上的資料,一個是調用setOrientation,一個是設置transform。

參考iOS Orientation,想怎麼轉怎麼轉

1. transform的方式我沒有實現。

轉屏沒有問題,但是因爲項目用的是AutoLayout,所以修改view的bounds的時候,不起作用。沒有找到解決辦法。

2. setOrientation一開始不起作用。因爲設置了shouldAutoRotate爲NO。所以橫屏啓動的時候,也沒法轉成豎屏。

修改下

-(BOOL)shouldAutorotate{
    return UIInterfaceOrientationIsLandscape(self.interfaceOrientation);
}

這樣就是橫屏可以轉,豎屏不能轉。

也就能保證橫屏啓動的時候,可以轉成豎屏,但是轉成豎屏之後,就不再能轉成橫屏。(強制橫屏時,相反地,只允許豎屏轉)

強制轉屏的代碼:

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        int val = UIInterfaceOrientationPortrait;
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }
    
    //...
}



發佈了34 篇原創文章 · 獲贊 1 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章