目录

如何使Popup宽度占满屏幕

问题现象

使用bindPopup创建气泡弹窗,如何使气泡弹窗的宽度占满屏幕?

效果预览

背景知识

bindPopup方法中填入的Popup参数有两种类型,PopupOptions和CustomPopupOptions:

解决方案

选用CustomPopupOptions类型的参数,并依靠自定义构建函数@Builder构建内容。

将CustomPopupOptions中的width设为100%:

@Entry
@Component
struct PopupWidth {
  @State handlePopup: boolean = false;

  @Builder
  popupBuilder() {
    Row({ space: 2 }) {
      Text('Custom Popup').fontSize(12);
    }.width(100).height(50).padding(5);
  }

  build() {
    Column({ space: 100 }) {
      Button('CustomPopupOptions中width设置为100%')
        .onClick(() => {
          this.handlePopup = !this.handlePopup;
        })
        .bindPopup(this.handlePopup, {
          width: '100%',
          builder: this.popupBuilder,
          arrowPointPosition: ArrowPointPosition.START, // 设置箭头的位置
          backgroundBlurStyle: BlurStyle.NONE, // 关闭气泡的模糊背景
          autoCancel: true,
        });
    }
    .margin({ top: 50 })
    .width('100%');
  }
}

常见FAQ

Q:使用Popup时,创建监听,会导致崩溃,是什么原因?

aboutToAppear(): void {
  this.listener.on('draw', () => {
    this.pageMainContentHeight = componentUtils.getRectangleById('pageMainContent').size.height // 单位是px
  })
}

A:使用Popup时要手动取消监听。

aboutToDisappear() {
  // Unregister callback before destruction
  this.listener.off('draw', () => {});
}