iOS 全局禁止横屏,但视频播放界面选择性横屏的解决办法

本文介绍了一种在iOS应用中灵活控制横屏显示的方法。通过在AppDelegate中添加一个布尔属性来控制整个应用是否允许横屏,并利用UIWindow的通知来实现视频播放时自动横屏、退出全屏时自动竖屏的效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有时我们的APP并没有适配横屏的需求,但是在个别视频播放界面,我们需要在播放视频的时候横屏,退出全屏的时候不能横屏,但是有时候并没有原生API并没有给出解决方案。

当其他界面不支持横屏时:

这个解决方法比较容易

在 APPDelegate.h 文件中增加属性:是否支持横屏

?
1
2
/***  是否允许横屏的标记 */
@property (nonatomic,assign)BOOL allowRotation;

在 APPDelegate.m 文件中增加方法,控制全部不支持横屏

?
1
2
3
4
5
6
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
     if (self.allowRotation) {
         return  UIInterfaceOrientationMaskAllButUpsideDown;
     }
     return UIInterfaceOrientationMaskPortrait;
}

这样在其他界面想要横屏的时候,我们只要控制 allowRotation 这个属性就可以控制其他界面进行横屏了。

?
1
2
3
4
//需在上面#import "AppDelegate.h"
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.allowRotation = YES;
//不让横屏的时候 appDelegate.allowRotation = NO;即可

播放界面横屏

所以这里可以使用 UIWindow 的通知,就可以解决

?
1
2
[[NSNotificationCenter defaultCenter] addObserver:self selector: @selector (begainFullScreen) name:UIWindowDidBecomeVisibleNotification object:nil]; //进入全屏
[[NSNotificationCenter defaultCenter] addObserver:self selector: @selector (endFullScreen) name:UIWindowDidBecomeHiddenNotification object:nil]; //退出全屏

在退出全屏时,增加逻辑让其强制编程竖屏,这样当全屏播放的时候,点击 down("完成") 时,就会自动变成竖屏了。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 进入全屏
-( void )begainFullScreen
{
     AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
     appDelegate.allowRotation = YES;
}
// 退出全屏
-( void )endFullScreen
{
     AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
     appDelegate.allowRotation = NO;
 
     //强制归正:
     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];
     }
}
亦可以建一baseViewController 其他控制器继承base 在base里设置禁止横屏 某一页面需要横屏 设置一下即可
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值