【问题标题】:Ionic 4 page dimensions after orientation change方向更改后的 Ionic 4 页面尺寸
【发布时间】:2019-11-26 22:05:01
【问题描述】:

我的 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,有什么想法吗?

【问题讨论】:

  • 尝试用布尔值检查 isResize 条件?

标签: ionic-framework ionic4


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2015-02-16
    • 1970-01-01
    • 2019-05-22
    • 1970-01-01
    • 2015-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多