APP 横屏和竖屏

51 篇文章 6 订阅
44 篇文章 0 订阅

普通情况下,APP 随着用户拿手机是横向还是竖向,自动翻转 -- 当然,这个也需要用户设置手机的屏幕是否跟随手机的物理方向而翻转。

但如果我们的APP,在某种情况下,必须以竖屏方式显示,在某种情况下,必须以横屏方式显示,不管用户是否把手机横过来放。该怎么办?

网上搜了一堆东西出来。安卓的资料比较多一点,iOS 的就很少了。最终解决了这个问题。大概代码如下:

uses {$IFDEF IOS}iOSapi.UIKit{$ENDIF};

-----------------------------

procedure LockOrientations_iOS(ATo: TScreenOrientation; APossibles: TScreenOrientations);
{$IFDEF IOS}
var
  win : UIWindow;
  App : UIApplication;
  new : UIViewController;
  old : UIViewController;
  toio: UIInterfaceOrientation;
{$ENDIF}
begin
{$IFDEF IOS}
  Application.FormFactor.Orientations := [];
  App := TUIApplication.Wrap(TUIApplication.OCClass.sharedApplication);
  win := TUIWindow.Wrap(App.windows.objectAtIndex(0));
  case ATo of
    TScreenOrientation.Portrait: toio := UIInterfaceOrientationPortrait;
    TScreenOrientation.Landscape: toio := UIInterfaceOrientationLandscapeLeft;
    TScreenOrientation.InvertedLandscape: toio := UIInterfaceOrientationLandscapeRight;
    else //TScreenOrientation.InvertedPortrait
      toio := UIInterfaceOrientationPortraitUpsideDown;
  end;
  App.setStatusBarOrientation(toio);
  Application.FormFactor.Orientations := APossibles;
  new := TUIViewController.Wrap(TUIViewController.alloc.init);
  old := win.rootViewController;
  Win.setRootViewController(new);
  Win.makeKeyAndVisible;
  win.setRootViewController(old);
  win.makeKeyAndVisible;
{$ENDIF}
end;

----------------------

function ChangeScreenOrientation(const AIsLandscap: Boolean = true): Integer;

function ChangeScreenOrientation(const AIsLandscap: Boolean = true): Integer;
var
  ScreenService: IFMXScreenService;
  OrientSet: TScreenOrientations;
{$IFDEF IOS}
  screenSet: TScreenOrientation;
{$ENDIF}
begin
{$IFDEF ANDROID}
  //强制横屏。这段代码对安卓有用。网上看到的说法是对 iOS 无用。需要对 iOS 进行测试。pcplayer
  if TPlatformServices.Current.SupportsPlatformService(IFMXScreenService, IInterface(ScreenService)) then
  begin
    if AIsLandscap then //横屏显示
      OrientSet := [TScreenOrientation.soLandscape]
    else
      OrientSet := [TScreenOrientation.Portrait];
    ScreenService.SetScreenOrientation(OrientSet);
  end;
{$ENDIF}

{$IFDEF IOS}
  if AIsLandscap then //横屏显示
  begin
    OrientSet := [TScreenOrientation.soLandscape];
    screenSet := TScreenOrientation.Landscape;
  end
  else
  begin
    OrientSet := [TScreenOrientation.Portrait];
    screenSet := TScreenOrientation.Portrait;
  end;
  LockOrientations_iOS(screenSet, OrientSet);
{$ENDIF}
end;

使用:程序调用 ChangeScreenOrientation 这个方法,可以设置横屏或竖屏。iOS 和 Android 都可以。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值