前言
編程的世界里, 存在各種各樣的需求創(chuàng)意,近期一個(gè)功能需求需要做到單個(gè)個(gè)別手機(jī)頁(yè)面需要做橫屏處理. 話不多說(shuō). 下面介紹一下代碼實(shí)現(xiàn)
原生橋接
因?yàn)榛趓eact-native開發(fā), 嘗試直接理由現(xiàn)有第三方庫(kù)實(shí)現(xiàn),例如:react-native-orientation,但是發(fā)現(xiàn)如果x-code里面deployment info設(shè)置不允許橫屏. 這個(gè)組件好像并沒(méi)有什么用處.

不允許橫屏設(shè)置.png
實(shí)現(xiàn)思路就是利用原生橋接一個(gè)工具類,通過(guò)這個(gè)類調(diào)用原生組件屬性去強(qiáng)制執(zhí)行
iOS原生修改
AppDelegate.h代碼片段
@property(nonatomic,assign)BOOL allowRotation;
@property(nonatomic, copy)NSString *direction;
AppDelegate.m代碼片段
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window
{
if ([self.direction isEqualToString:@"right"]) {
//橫屏
return UIInterfaceOrientationMaskLandscape;
} else{
//豎屏
return UIInterfaceOrientationMaskPortrait;
}
}
DeviceOrientation.m全部代碼
#import "DeviceOrientation.h"
#import "AppDelegate.h"
@implementation DeviceOrientation
RCT_EXPORT_MODULE();
RCT_EXPORT_METHOD(orientation: (NSString *)direction) {
dispatch_async(dispatch_get_main_queue(), ^{
AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
appDelegate.allowRotation = YES;
appDelegate.direction = direction;
[[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIInterfaceOrientationPortrait] forKey:@"orientation"];
NSNumber * number;
if ([direction isEqualToString:@"right"]) {
number = [NSNumber numberWithInteger:UIInterfaceOrientationLandscapeRight];
[[UIDevice currentDevice] setValue:number forKey:@"orientation"];
} else if ([direction isEqualToString:@"left"]) {
number = [NSNumber numberWithInteger:UIInterfaceOrientationLandscapeLeft];
[[UIDevice currentDevice] setValue:number forKey:@"orientation"];
}
});
}
@end
這是一個(gè)iOS橋接的工具類, 在js中調(diào)用即可
android原生修改
public class DeviceOrientation extends ReactContextBaseJavaModule {
public DeviceOrientation(ReactApplicationContext reactContext) {
super(reactContext);
}
@Override
public String getName() {
return "DeviceOrientation";
}
@ReactMethod
public void orientation(String direction) {
Activity currentActivity = getCurrentActivity();
if(direction.equals("right")) {
currentActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
} else {
currentActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
}
這是一個(gè)android橋接的工具類, 在js中調(diào)用即可. 調(diào)用名稱跟iOS名稱相同, 方便js中使用
js使用
新建一個(gè)deviceUtils.js文件
const { NativeModules } = require('react-native');
module.exports = NativeModules.DeviceOrientation;
在頁(yè)面直接使用deviceUtils方法即可
DeviceOrientationUtils.orientation('right');
有問(wèn)題或者建議的同學(xué),歡迎留言討論