iOS強(qiáng)制某個(gè)界面橫屏的方法

在AppDelegate中添加方法關(guān)閉橫豎屏切換,方法如下

1.AppDelegate.h中外露一個(gè)屬性

@property(nonatomic,assign)BOOL allowRotation;//是否允許轉(zhuǎn)向


2.AppDelegate.m中添加方法(如果屬性值為YES,僅允許屏幕向左旋轉(zhuǎn),否則僅允許豎屏)

- (UIInterfaceOrientationMask)application:(UIApplication

*)application supportedInterfaceOrientationsForWindow:(nullable UIWindow

*)window

{

? ? if (_allowRotation == YES) {

? ? ? ? return UIInterfaceOrientationMaskLandscapeLeft;

? ? }else{

? ? ? ? return (UIInterfaceOrientationMaskPortrait);

? ? }

}


第三步:

1.在需要強(qiáng)制橫屏的控制器.m中添加旋轉(zhuǎn)為橫屏方法

- (void)setNewOrientation:(BOOL)fullscreen

{

if (fullscreen) {

? ? ? ? NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];

? ? ? ? [[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];


? ? ? ? NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];

? ? ? ? [[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"];

? ? }

}


2.view DidLoad中添加以下代碼

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

? ? appDelegate.allowRotation = YES;//(以上2行代碼,可以理解為打開橫屏開關(guān))

[self setNewOrientation:YES];//調(diào)用轉(zhuǎn)屏代碼


3.重寫導(dǎo)航欄返回箭頭按鈕,拿到返回按鈕點(diǎn)擊事件

- (void)back

{

? ? AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

? ? appDelegate.allowRotation = NO;//關(guān)閉橫屏僅允許豎屏

? ? [self setNewOrientation:NO];

? ? [self.navigationController popViewControllerAnimated:YES];

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容