应用本身只支持竖屏,当时又想让应用中网页视频可以全屏播放,这种需求想必经常会有。
这里提供一种方法,经过测试,能实现这种需求。
以下代码在Xcode7.1,iOS6~iOS9 测试通过。
首先在xxxxAppDelegate中增加一个属性:
@property (nonatomic, assign) BOOL allowRotation; // 标记是否可以旋转
.m文件中实现方法:
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)nowWindow {
if (_allowRotation) {
return UIInterfaceOrientationMaskAll;
}
else
{
return UIInterfaceOrientationMaskPortrait;
}
}
Webview进入视频播放页面时候,系统会发出几个通知:
UIMoviePlayerControllerDidEnterFullscreenNotification // 进入全屏播放
UIMoviePlayerControllerWillExitFullscreenNotification // 将退出全屏播放
UIMoviePlayerControllerDidExitFullscreenNotification // 已退出全屏播放
因此,可以在包含Webview的Controller的viewDidLoad方法中添加两个通知监听,分别是:
- (void)viewDidLoad
{
[super viewDidLoad];
if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0f || [[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0f) {
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(videoStarted:) name:@"UIMoviePlayerControllerDidEnterFullscreenNotification" object:nil];// 播放器即将播放通知
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(videoFinished:) name:@"UIMoviePlayerControllerWillExitFullscreenNotification" object:nil];// 播放器即将退出通知
}
else
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoStarted:) name:UIWindowDidBecomeVisibleNotification object:nil];//进入全屏
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoFinished:) name:UIWindowDidBecomeHiddenNotification object:nil];//退出全屏
}
}
#pragma - mark 视频进入全屏
-(void)videoStarted:(NSNotification *)notification
{
xxxxAppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
appDelegate.allowRotation = YES;
}
#pragma - mark 视频将退出
-(void)videoWillFinished:(NSNotification *)notification
{
xxxxAppDelegate *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];
}
}
Over。
参考资料
- http://www./sj/ios8/90517.htm
|