iOS下react-native-video调用presentFullscreenPlayer时如何直接转为横屏
解决react-native-video全屏直接横屏的问题
我之前也碰到过类似的困扰,用react-native-orientation配合调用确实经常不生效——毕竟原生播放器的全屏逻辑会优先接管屏幕方向,JS层的锁方向操作容易被覆盖。直接修改RTCVideo.m里的setFullscreen函数是最直接的解决方案,下面给你一步步拆解:
1. 定位目标文件
找到你项目中react-native-video的iOS原生代码文件,路径通常是:node_modules/react-native-video/ios/RTCVideo.m
2. 修改setFullscreen函数
先找到默认的setFullscreen:方法,大概是这样的:
- (void)setFullscreen:(BOOL)fullscreen { if (_isFullscreen == fullscreen) { return; } _isFullscreen = fullscreen; if (fullscreen) { [self presentFullscreenPlayer]; } else { [self dismissFullscreenPlayer]; } [self sendOnFullscreenChange]; }
我们需要在调用presentFullscreenPlayer前强制锁定横屏,同时兼顾iOS版本兼容(尤其是iOS16+的新API)。修改后的代码如下:
- (void)setFullscreen:(BOOL)fullscreen { if (_isFullscreen == fullscreen) { return; } _isFullscreen = fullscreen; if (fullscreen) { // 强制切换为横屏 if (@available(iOS 16.0, *)) { // iOS16+ 使用UIWindowScene API设置方向 UIWindowScene *windowScene = [UIApplication sharedApplication].connectedScenes.firstObject; if ([windowScene isKindOfClass:[UIWindowScene class]]) { UIWindowSceneGeometryPreferencesIOS *geometryPrefs = [[UIWindowSceneGeometryPreferencesIOS alloc] initWithInterfaceOrientations:UIInterfaceOrientationMaskLandscape]; [windowScene requestGeometryUpdateWithPreferences:geometryPrefs errorHandler:^(NSError * _Nonnull error) { NSLog(@"横屏设置失败:%@", error); }]; } } else { // iOS16以下使用传统方法 [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationLandscapeRight) forKey:@"orientation"]; [UIViewController attemptRotationToDeviceOrientation]; } [self presentFullscreenPlayer]; } else { [self dismissFullscreenPlayer]; // 退出全屏后恢复竖屏(可根据需求选择是否保留) if (@available(iOS 16.0, *)) { UIWindowScene *windowScene = [UIApplication sharedApplication].connectedScenes.firstObject; if ([windowScene isKindOfClass:[UIWindowScene class]]) { UIWindowSceneGeometryPreferencesIOS *geometryPrefs = [[UIWindowSceneGeometryPreferencesIOS alloc] initWithInterfaceOrientations:UIInterfaceOrientationMaskPortrait]; [windowScene requestGeometryUpdateWithPreferences:geometryPrefs errorHandler:nil]; } } else { [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationPortrait) forKey:@"orientation"]; [UIViewController attemptRotationToDeviceOrientation]; } } [self sendOnFullscreenChange]; }
3. 关键配置补充
别忘了在iOS项目的Info.plist中添加横屏支持:
在Supported interface orientations列表里,加入Landscape (left home button)和Landscape (right home button),确保应用允许横屏旋转。
4. 后续注意事项
- 修改
node_modules里的文件后,建议用patch-package保存修改,避免下次npm install时被覆盖。 - 如果你的项目存在多窗口场景,可能需要调整获取
windowScene的逻辑(比如遍历所有connectedScenes找到当前活跃的窗口)。 - 记得在不同iOS版本的设备上测试兼容性,尤其是iOS16及以上的机型。
这样修改后,调用this.player.presentFullscreenPlayer()时,播放器就会直接以横屏状态启动,不会再出现竖屏转横屏的卡顿或不生效问题了。
内容的提问来源于stack exchange,提问作者FeelRightz
相关产品推荐
相关产品推荐

