@CustomDialog
struct CustomDialogExample {
controller?: CustomDialogController;
build() {
Column({ space: 24 }) {
Text('这是自定义弹窗')
.maxLines(1)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.fontSize(16);
Button('Close')
.onClick(() => {
if (this.controller !== undefined) {
this.controller.close();
}
});
}.padding(24);
}
}
@Entry
@Component
struct CustomDialogUser {
dialogController: CustomDialogController | null = null;
aboutToAppear(): void {
this.createDialogCtl(300); // 创建CustomDialogController对象,宽度300
}
aboutToDisappear() {
this.dialogController = null; // 将dialogController置空
}
// 创建宽度不同的新弹窗
createDialogCtl(width: number): void {
this.dialogController = new CustomDialogController({
builder: CustomDialogExample(),
autoCancel: true,
alignment: DialogAlignment.Center,
offset: { dx: 0, dy: -20 },
customStyle: false,
cornerRadius: 20,
width: width,
backgroundColor: Color.White,
});
}
build() {
Column({ space: 24 }) {
Button('click me')
.onClick(() => {
if (this.dialogController != null) {
this.dialogController.open();
}
});
Button('change')
.onClick(() => {
this.createDialogCtl(150); // 创建新的CustomDialogController对象,宽度150
});
}.width('100%').margin({ top: 16 });
}
} import { ComponentContent } from '@kit.ArkUI';
interface ParamsInterface {
text: string;
}
@Builder
function buildText(params: ParamsInterface) {
Column() {
Text(params.text)
.fontSize(24);
}.padding(24)
.borderRadius(16)
.justifyContent(FlexAlign.Center)
.backgroundColor(Color.White);
}
@Entry
@Component
struct ComponentContentDemo {
build() {
Column() {
Button('click me')
.onClick(() => {
let uiContext = this.getUIContext();
let promptAction = uiContext.getPromptAction();
// 自定义弹窗的内容
let contentNode = new ComponentContent<ParamsInterface>(uiContext, wrapBuilder<[ParamsInterface]>(buildText),
{ text: 'old style' });
promptAction.openCustomDialog(contentNode);
setTimeout(() => {
contentNode.update({ text: 'new style' });
}, 2000); // 2秒后自动更新弹窗内容文本
});
}.width('100%').height('100%').margin({ top: 16 });
}
} Q:CustomDialog的offset能不能响应式更新?
A:自定义弹窗(CustomDialog)的所有参数,不支持动态刷新。推荐使用不依赖UI组件的全局自定义弹出框 (openCustomDialog)。
Q:如何让dialog在隐藏的情况下,再展示时,数据不消失?
A:可以将弹窗数据同步保存至父组件中,可以参考使用@Link和@Consume监听数据变化。
Q:如何设置弹窗的位置,使其弹出到屏幕上层?
A:可以修改CustomDialogControllerOptions对象的offset参数,实现改变弹窗的位置。