- 針對(duì)項(xiàng)目中整體豎屏顯示绞吁,某頁(yè)面需要旋轉(zhuǎn)的場(chǎng)景恬惯,解決方案如下:
1. 設(shè)置項(xiàng)目支持方向
- 僅勾選豎屏
image.png
2. AppDelegate中添加一個(gè)屬性排宰,記錄是否允許旋轉(zhuǎn)
/// 是否允許旋轉(zhuǎn)
@property (assign, nonatomic) BOOL allow;
- 實(shí)現(xiàn) supportedInterfaceOrientationsForWindow 方法
//根據(jù)設(shè)置調(diào)整支持方向
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
if (self.allow) {
return UIInterfaceOrientationMaskAllButUpsideDown;
}
return UIInterfaceOrientationMaskPortrait;
}
3. 創(chuàng)建控制器基類官辽,便于操作
- 創(chuàng)建控制器時(shí)應(yīng)繼承于基類
- 在基類中實(shí)現(xiàn)以下方法
//基類:默認(rèn)不支持旋轉(zhuǎn)
- (BOOL)shouldAutorotate {
return NO;
}
//默認(rèn)支持方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
return UIInterfaceOrientationMaskPortrait;
}
4. 針對(duì)項(xiàng)目架構(gòu) TabBarController + NavigationController
- 在自定義的 NavigationController 中設(shè)置跟隨控制器的設(shè)置
//跟隨當(dāng)前顯示控制器的設(shè)置
- (BOOL)shouldAutorotate {
return self.topViewController.shouldAutorotate;
}
- 在自定義的 TabBarController 中設(shè)置跟隨選中導(dǎo)航控制器的設(shè)置
//跟隨當(dāng)前導(dǎo)航控制器的設(shè)置
- (BOOL)shouldAutorotate {
return self.selectedViewController.shouldAutorotate;
}
5. 在想要旋轉(zhuǎn)的控制器中實(shí)現(xiàn)以下方法
- 導(dǎo)入 AppDelegate
//打開允許旋轉(zhuǎn)
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
((AppDelegate *)[[UIApplication sharedApplication] delegate]).allow = YES;
}
//關(guān)閉允許旋轉(zhuǎn)
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
((AppDelegate *)[[UIApplication sharedApplication] delegate]).allow = NO;
}
//支持旋轉(zhuǎn)
- (BOOL)shouldAutorotate {
return YES;
}
至此汛聚,已實(shí)現(xiàn)以上需求。
完整Demo已上傳穿香,點(diǎn)擊這里查看 ScreenRotationDemo