DEV Community

HarmonyOS
HarmonyOS

Posted on

Drag the module to the specified location

Read the original article:Drag the module to the specified location

Problem Description

Implement the functionality of dragging a module to a specified position.

Background Knowledge

PanGesture is a swipe gesture event that triggers when the minimum swipe distance reaches the set minimum value.

Solution

You can use @State to track position offsets and final coordinates, combine it with the PanGesture gesture event to update coordinates in real-time, and trigger the translate method to dynamically adjust the component's position, achieving the effect of staying in place after dragging. The example code is as follows:

  • Use @State to track the position state, distinguishing between temporary offsets and final positions.
  • Listen to drag events through PanGesture, update offsets in real-time, and save the final position at the end.
  • Use the translate method to dynamically adjust the component's position based on the state value, achieving the drag effect.
@Entry
@Component
struct GestureDemo {
  build() {
    Column({ space: 10 }) {
      Row() {
      }
      .width(300)
      .height(200)
      .border({ color: Color.Red, width: 1 })

      Row({ space: 5 }) {
        Repeat(new Array(5).fill('0').map((item: string, index) => item + index))
          .each((repeat) => {
            GestureItem({ text: repeat.item })
          })
      }
      .width(300)
      .height(60)
      .border({ color: Color.Blue, width: 1 })
      .padding(10)
    }.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 = ''
  siz: number = 50
  ratio: number = 1.2

  build() {
    Row() {
      Text(this.text)
    }
    .width(this.siz)
    .aspectRatio(this.ratio)
    .border({ color: Color.Blue, width: 1 })
    .translate({ x: this.offsetX, y: this.offsetY, z: 0 })
    .gesture(
      PanGesture() // When the drag gesture is triggered, modify the layout position information of the component according to the callback function.
        .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;
        })
    )
  }
}
Enter fullscreen mode Exit fullscreen mode

The effect is as follows:

Written by Aycanur Ucar

Top comments (0)