Flutter 屏幕旋轉(zhuǎn)
已發(fā)布github, 以下文章為采坑記錄, 無感可直接使用.
以下為git依賴, 可下載git源碼, 運行 example 查看使用
dependencies:
flutter:
sdk: flutter
orientation_ios:
git:
url: https://github.com/yangyangFeng/orientation_ios.git
tag: 1.1.0
1.如何實踐屏幕屏幕旋轉(zhuǎn)
1.1 flutter 官方API
//iOS不生效
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeLeft,
DeviceOrientation.landscapeRight,
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown
]);
1.2 pub 開源組件
orientation //iOS不生效
2. iOS如何旋轉(zhuǎn)指定頁面
既然flutter不支持,那么我們只能通過iOS native來實現(xiàn)此功能,并且以接口的方式提供給flutter調(diào)用, 也就是flutter所說的plugin.
2.1 創(chuàng)建flutterplugin
資料比較多,不再復述啦.
2.2 iOS旋轉(zhuǎn)功能支持
這里區(qū)分兩種場景
1 支持所有方向, 各個頁面方向不同.
全部方向
//如果xcode已經(jīng)設置支持全部方向,那么比較簡單,直接強制旋轉(zhuǎn)就ok了.
NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
[[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
2 只支持一種方向, 某個頁面支持其他方向.
橫屏應用
這種情況,因為啟動圖和app的方向只支持橫屏, 但是個別頁面缺要求其他方向(比如說豎屏)
這里我們要通過Appdelegate
中的協(xié)議動態(tài)返回APP所支持的方向.
@implementation AppDelegate (Orientation)
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
//將要動態(tài)支持的方向
return self.orientationMask;
}
修改好我們將要旋轉(zhuǎn)的方向(協(xié)議返回的支持方向),比如下邊我將由目前的橫屏
轉(zhuǎn)為豎屏
AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//將設備支持方向設置為豎屏
delegate.orientationMask = UIInterfaceOrientationMaskPortrait;
可以繼續(xù)上述第一步強制旋轉(zhuǎn)即可, 強制旋轉(zhuǎn)為豎屏
//如果xcode已經(jīng)設置支持全部方向,那么比較簡單,直接強制旋轉(zhuǎn)就ok了.
//修改`self.orientationMask`屬性, 與修改xcode支持方向, 效果相同.
NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
[[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
3. 最終結(jié)果
iOS核心方法其實就是強制屏幕旋轉(zhuǎn), 不過它有諸多限制, 比如:
- xcode方向支持,沒有動態(tài)性.
- 非iOS開發(fā)者, 不熟悉native
UIViewController
和 設備旋轉(zhuǎn)的區(qū)別. 純flutter只能通過設備旋轉(zhuǎn),來達到旋轉(zhuǎn)指定頁面.
為了不侵入Appdelegate文件,我通過分類的方式支持動態(tài)修改APP支持方向,以便于后期當做flutter pulgin發(fā)布
下面貼一下分類代碼吧
AppDelegate+Orientation.h
#import "AppDelegate.h"
NS_ASSUME_NONNULL_BEGIN
@interface AppDelegate (Orientation)
@property(assign,nonatomic)UIInterfaceOrientationMask orientationMask;
@end
NS_ASSUME_NONNULL_END
AppDelegate+Orientation.m
#import "AppDelegate+Orientation.h"
#import <objc/runtime.h>
static char* const kOrientationMask;
@implementation AppDelegate (Orientation)
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
return self.orientationMask;
}
- (void)setOrientationMask:(UIInterfaceOrientationMask)OrientationMask{
objc_setAssociatedObject(self, kOrientationMask, @(OrientationMask), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (UIInterfaceOrientationMask)orientationMask{
return[(NSNumber *)objc_getAssociatedObject(self, kOrientationMask) intValue];
}
@end