以強制豎屏爲例,強制橫屏同理。
如果要全部豎屏,直接在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。
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];
}
//...
}