自学内容网 自学内容网

HarmonyOS(45) 控件拖动或者拖拽PanGesture

PanGesture实现控件拖动的效果,通过拖动的坐标位置调用position或者translate方法来更新UI的位置。效果见下图:

在这里插入图片描述
具体代码如下:

// xxx.ets


struct PanGestureExample {
   offsetX: number = 0
   offsetY: number = 0
  positionX: number = 0
  positionY: number = 0
  private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.All })

  build() {
    Column() {
      Column() {
        Text('PanGesture offset:\nX: ' + this.offsetX + '\n' + 'Y: ' + this.offsetY)
      }
      .height(200)
      .width(300)
      .padding(20)
      .border({ width: 3 })
      .margin(50)
      .onClick(()=>{
        console.info('Pan click')
      })
      .translate({ x: this.offsetX, y: this.offsetY }) // 以组件左上角为坐标原点进行移动,此处也可以调用position({ x: this.offsetX, y: this.offsetY }) 方法
      // 左右拖动触发该手势事件
      .gesture(
        PanGesture(this.panOption)
          .onActionStart((event: GestureEvent) => {
            console.info('Pan start')
          })
          .onActionUpdate((event: GestureEvent) => {
            if (event) {
              this.offsetX = this.positionX + event.offsetX
              this.offsetY = this.positionY + event.offsetY
            }
          })
          .onActionEnd((event: GestureEvent) => {
            //记录拖动结束前停留的位置
            this.positionX = this.offsetX
            this.positionY = this.offsetY
            console.info('Pan end')
          })
      )
    }
  }
}

通过这个PanGesture,可以实现更复杂的功能,比如ListView的item排序等,后面会写相关博文出来。
参考资料:
HarmonyOS(40) 悬浮框实现
PanGesture


原文地址:https://blog.csdn.net/chunqiuwei/article/details/140691036

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!