可通过@State跟踪位置偏移与最终坐标,结合PanGesture手势事件实时更新坐标并触发translate方法动态调整组件位置,实现拖动后停留的效果,具体步骤如下:
完整示例参考如下:
@Entry @Component struct GestureDemo { build() { Column({ space: 16 }) { TextInput() .width(350) .height(400); Row({ space: 5 }) { Repeat(new Array(5).fill('0').map((item: string, index) => item + index)) .each((repeat) => { GestureItem({ text: repeat.item }); }); } .width(350) .height(80) .border({ color: Color.Blue, width: 1, radius: 16 }) .padding(10); } .padding(24) .alignItems(HorizontalAlign.Center) .width('100%') .height('100%'); } } @Component export struct GestureItem { @State offsetX: number = 0; @State offsetY: number = 0; @State positionX: number = 0; @State positionY: number = 0; text: string = ''; build() { Button() { Text(this.text); } .backgroundColor('#0a59f7') .width(60) .translate({ x: this.offsetX, y: this.offsetY, z: 0 }) .gesture( PanGesture() // 当触发滑动手势时,根据回调函数修改组件的布局位置信息 .onActionUpdate((event: GestureEvent | undefined) => { if (event) { this.offsetX = this.positionX + event.offsetX; this.offsetY = this.positionY + event.offsetY; } }) .onActionEnd(() => { this.positionX = this.offsetX; this.positionY = this.offsetY; }) ); } }