首页 > 解决方案 > 方向更改后的 Ionic 4 页面尺寸

问题描述

我的 Ionic 应用程序中有一个组件,它需要屏幕尺寸。Platform在用户更改其设备的方向后,我正在尝试使用该插件来获取新的屏幕尺寸。我正在尝试使用以下代码执行此操作:

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.scss'],
})
export class MyComponent implements OnInit, OnDestroy {
  deviceWidth: number;
  deviceHeight: number;
  subs = new Subscription();

  constructor(private platform: Platform) {}

  ngOnInit() {
    subs.add(this.platform.resize.subscribe(async () => {
      this.deviceWidth = this.platform.width();
      this.deviceHeight = this.platform.height();
      console.log(this.platformHeight, this.platformWidth);
    });
  }

  ngOnDestroy() {
    this.subs.unsubscribe();
  }
}

我遇到的问题是platform.resize在动画/过渡到新方向完成之前调用。因此,platform.height()platform.width()是不正确的(它们都被设置为设备的最小尺寸)。为了对此进行测试,我为我的 resize 订阅尝试了以下操作:

    subs.add(this.platform.resize.subscribe(async () => {
      console.log(`Initial Call- width: ${this.platform.width}, height: ${this.platform.height}`);
      setTimeout({ // wait until long after the transition animation
        console.log(`After Transition- width: ${this.platform.width}, height: ${this.platform.height}`);
      }, 1000);
    });

在从横向更改为纵向后,会产生以下结果:

Initial Call- width: 414, height: 414
After Transition- width: 414, height: 896

关于如何获得正确的宽度/高度,而不setTimeout在订阅中插入一些随机的任何想法?

标签: ionic-frameworkionic4

解决方案


我为我的应用找到的最佳方式是使用屏幕方向(https://ionicframework.com/docs/v3/native/screen-orientation/)。使用该框架,您可以检查横向/纵向方向。

然后在您的情况下,您只需要在两个 IF 中做出承诺,以便在每个方向上获得适当的尺寸


推荐阅读