屏幕底部有一个按钮,当出现半模态组件时,需要将该按钮向上移动,以避让半模态组件。在半模态组件高度动态变化(非手势触发)的情况下,该按钮应始终与半模态组件保持固定距离,并实现平滑跟随效果。如何实现这一功能?
import { curves, LengthUnit } from '@kit.ArkUI';
@Entry
@Component
export struct BindSheetAnimateDemo {
private sheetHeights: number[] = [100, 200, 300];
private index: number = 0;
@State showSheet: boolean = false;
@State dataList: string[] = [];
@State detentSelectionVal: number = 0;
@State marginVal: number = 0;
aboutToAppear(): void {
this.dataList = Array(30).fill(0).map((_value: number, index: number) => String(index));
}
@Builder
demoBuilder() {
List() {
ForEach(this.dataList, (item: string) => {
ListItem() {
Text(item)
.fontSize('18fp')
.height('30vp')
.margin({ left: 20 })
.textAlign(TextAlign.Center);
};
});
}
.width('100%');
}
build() {
Stack() {
Column() {
Button('切换')
.width('90%')
.height(44)
.borderRadius(22)
.onClick(() => {
if (!this.showSheet) {
return;
}
this.detentSelectionVal = this.sheetHeights[(++this.index) % 3];
this.getUIContext()?.animateTo({ curve: curves.springMotion() }, () => {
this.marginVal = this.detentSelectionVal;
});
})
.margin({ bottom: 16, top: 50 });
Button('按钮').width('90%').height(44).borderRadius(22).margin({ bottom: this.marginVal + 16 });
}.height('100%').width('100%').justifyContent(FlexAlign.End);
Text('打开半模态页面')
.fontSize('20fp')
.fontColor('#000000')
.textAlign(TextAlign.Center)
.onClick(() => {
this.showSheet = !this.showSheet;
this.detentSelectionVal = this.showSheet ? this.sheetHeights[0] : 0;
this.getUIContext()?.animateTo({ curve: curves.springMotion() }, () => {
this.marginVal = this.detentSelectionVal;
});
})
.bindSheet(this.showSheet, this.demoBuilder(), {
detentSelection: this.detentSelectionVal,
detents: [100, 200, 300],
enableOutsideInteractive: true,
radius: { value: 4, unit: LengthUnit.VP },
showClose: false,
mode: SheetMode.EMBEDDED,
preferType: SheetType.BOTTOM,
scrollSizeMode: ScrollSizeMode.CONTINUOUS, // 半模态面板在滑动过程中持续更新内容显示区域。
onHeightDidChange: (height) => {
// 手动调整半模态高度时,保持跟随
this.marginVal = this.getUIContext().px2vp(height);
}
})
.width('100%');
}
.height('100%')
.width('100%')
.alignContent(Alignment.Top);
}
}