HarmonyOS鸿蒙Next中如何实现手势移动组件

HarmonyOS鸿蒙Next中如何实现手势移动组件 给一个组件添加垂直方向的滑动手势监听,根据手指滑动距离,实时的重新设置该组件的位置

1 回复

更多关于HarmonyOS鸿蒙Next中如何实现手势移动组件的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


可以通过组件的onTouch事件来监听手动滑动,并通过改变组件的translate的值来移动组件

@Entry
@Component
struct Page1 {
  @State translatey: number = 300
  InitialPosition: number = 0

  onTouchEvent(event: TouchEvent): void {
    switch (event.type) {
      //手指按下事件
      case TouchType.Down: {
      //记录手指摁下时所在的位置
        this.InitialPosition = event.touches[0].windowY
      }
     //手指按住移动
      case TouchType.Move: {
          this.translatey = this.translatey as number - (this.InitialPosition - event.touches[0].windowY)
          this.InitialPosition = event.touches[0].windowY
      }
      //手指抬起
      case TouchType.Up: {
      }
    }
  }

  build() {
    Column() {
      Column() {

      }
      .width('100%')
      .height(500)
      .backgroundColor(Color.Yellow)
      .translate({ y: this.translatey })
      .onTouch((event: TouchEvent) => {
        this.onTouchEvent(event)
      })
    }
    .justifyContent(FlexAlign.End)
    .height('100%')
    .width('100%')
    .backgroundColor(Color.Grey)
  }
}
回到顶部