Firemonkey扩展增强: iOS 运行时更改锁定显示方向(增强版)

之前在这里介绍过Firemonkey如何在运行时更改和锁定iOS设备的显示方向。这里给出一个改良优化的版本,增加考虑原先支持显示方向以减少不必要的重绘。

下载代码

unit TU2.iOS.Helper;

interface

uses FMX.Types;

  //更改屏幕方向
  procedure ChangeOrientations(APreferred: TScreenOrientation; ASupported: TScreenOrientations);

implementation

uses
  iOSapi.UIKit, FMX.Platform, FMX.Forms;

function GetOrientation(AOrientation: UIInterfaceOrientation): TScreenOrientation; overload;
begin
  case AOrientation of
    UIInterfaceOrientationPortrait: Result := TScreenOrientation.Portrait;
    UIInterfaceOrientationLandscapeLeft: Result := TScreenOrientation.Landscape;
    UIInterfaceOrientationLandscapeRight: Result := TScreenOrientation.InvertedLandscape;
    else
      Result := TScreenOrientation.InvertedPortrait;
  end;
end;

function GetOrientation(AOrientation: TScreenOrientation): UIInterfaceOrientation; overload;
begin
  case AOrientation of
    TScreenOrientation.Portrait: Result := UIInterfaceOrientationPortrait;
    TScreenOrientation.Landscape: Result := UIInterfaceOrientationLandscapeLeft;
    TScreenOrientation.InvertedLandscape: Result := UIInterfaceOrientationLandscapeRight;
    else //TScreenOrientation.InvertedPortrait
      Result := UIInterfaceOrientationPortraitUpsideDown;
  end;
end;

procedure ChangeOrientations(APreferred: TScreenOrientation; ASupported: TScreenOrientations);
var
  App : UIApplication;
  win : UIWindow;
  new,old : UIViewController;
begin
  Include(ASupported,APreferred);
  App := TUIApplication.Wrap(TUIApplication.OCClass.sharedApplication);
  if not (GetOrientation(App.statusBarOrientation) in ASupported) then
    App.setStatusBarOrientation(GetOrientation(APreferred));//Change stausbar orientations
  //Change Supported orientations
  if Application.FormFactor.Orientations<>ASupported then
  begin
    //The first Windows is always the main Window
    win := TUIWindow.Wrap(App.windows.objectAtIndex(0));
    //we store all our current content to the old ViewController
    old := win.rootViewController;
    {Now we are creating a new(dummy) Viewcontroller, after it is created,
    it will have to check what is the supported orientations}
    Application.FormFactor.Orientations := ASupported;
    new := TUIViewController.Wrap(TUIViewController.alloc.init);
    Win.setRootViewController(new);
    Win.makeKeyAndVisible;// We display the Dummy viewcontroller
    {And now we Display our original Content in a new Viewcontroller
     with our new Supported orientations}
    win.setRootViewController(old);
    win.makeKeyAndVisible;
  end;
end;

end.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值