Flutter 屏幕旋转Pulgin【iOS旋转失效问题】

Flutter 屏幕旋转

已发布github, 以下文章为采坑记录, 无感可直接使用.

以下为git依赖, 可下载git源码, 运行 example 查看使用

dependencies:
  flutter:
    sdk: flutter

  orientation_ios:
    git:
      url: https://github.com/yangyangFeng/orientation_ios.git
      tag: 1.1.0

1.如何实践屏幕屏幕旋转

1.1 flutter 官方API

 //iOS不生效
 SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeRight,
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown
    ]);

1.2 pub 开源组件
orientation //iOS不生效

2. iOS如何旋转指定页面

既然flutter不支持,那么我们只能通过iOS native来实现此功能,并且以接口的方式提供给flutter调用, 也就是flutter所说的plugin.

2.1 创建flutterplugin
资料比较多,不再复述啦.

2.2 iOS旋转功能支持
这里区分两种场景

1 支持所有方向, 各个页面方向不同.


全部方向
  //如果xcode已经设置支持全部方向,那么比较简单,直接强制旋转就ok了.
  NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
  [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];

2 只支持一种方向, 某个页面支持其他方向.

横屏应用

这种情况,因为启动图和app的方向只支持横屏, 但是个别页面缺要求其他方向(比如说竖屏)

这里我们要通过Appdelegate 中的协议动态返回APP所支持的方向.

@implementation AppDelegate (Orientation)

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
  //将要动态支持的方向
  return self.orientationMask;
}

修改好我们将要旋转的方向(协议返回的支持方向),比如下边我将由目前的横屏转为竖屏

  AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
  //将设备支持方向设置为竖屏
  delegate.orientationMask = UIInterfaceOrientationMaskPortrait;

可以继续上述第一步强制旋转即可, 强制旋转为竖屏

  //如果xcode已经设置支持全部方向,那么比较简单,直接强制旋转就ok了.
  //修改`self.orientationMask`属性, 与修改xcode支持方向, 效果相同.
  NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
  [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];

3. 最终结果

iOS核心方法其实就是强制屏幕旋转, 不过它有诸多限制, 比如:

  1. xcode方向支持,没有动态性.
  2. 非iOS开发者, 不熟悉native UIViewController 和 设备旋转的区别. 纯flutter只能通过设备旋转,来达到旋转指定页面.

为了不侵入Appdelegate文件,我通过分类的方式支持动态修改APP支持方向,以便于后期当做flutter pulgin发布
下面贴一下分类代码吧

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 

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

你可能感兴趣的:(Flutter 屏幕旋转Pulgin【iOS旋转失效问题】)