ionic-framework - 方向更改后的 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
在订阅中插入一些随机的任何想法?
解决方案
我为我的应用找到的最佳方式是使用屏幕方向(https://ionicframework.com/docs/v3/native/screen-orientation/)。使用该框架,您可以检查横向/纵向方向。
然后在您的情况下,您只需要在两个 IF 中做出承诺,以便在每个方向上获得适当的尺寸
推荐阅读
- android - 在android中使用递减和递增按钮编辑文本的最小值和最大值
- mysql - 在只读 mysql 数据库中声明一个变量
- reactjs - 包装 React Hook 返回值会导致渲染循环
- javascript - Javascript:按值将数组拆分为多个数组
- excel - VBA Application.OnTimeime 不循环
- python - numpy 数据存储在哪里?
- windows-subsystem-for-linux - 在 Linux 主机上运行的 Windows 10 来宾 VM 中运行 WSL2
- javascript - 为什么这个 span 标签只改变不到一秒钟?
- python - python上缩进代码块的解释
- android - Android:水平LinearLayout没有按预期布局元素