目录

如何解决组件消失后滑动手势依然可以触发的问题

问题现象

当组件在手势事件触发过程中,设置其Visibility为Visibility.None,组件隐藏后绑定的滑动手势事件依然可以触发。

问题效果预览:

效果预览

当组件消失后,手指滑动不会继续触发组件的手势事件。

背景知识

解决方案

当使用Visibility.None将组件隐藏后,组件虽然不占位,但onActionUpdate回调的接口还没有释放,行为上仍在触发。

可使用手势拦截增强,通过onGestureRecognizerJudgeBegin属性获取当前组件的识别器,当设置Visibility为None的时候通过手势识别器的setEnabled方法设置为false表示当前手势识别器不回调应用事件,从而实现禁止组件的拖拽事件。

@Entry
@Component
struct PanGestureExample {
  @State offsetX: number = 0;
  @State offsetY: number = 0;
  @State positionX: number = 0;
  @State positionY: number = 0;
  private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Left | PanDirection.Right });
  private currentRecognizer: GestureRecognizer = new GestureRecognizer();
  @State flag: boolean = true;

  aboutToAppear(): void {
    // 四秒后隐藏该组件
    setTimeout(() => {
      this.flag = false;
      // 设置当前手势识别器的使能状态
      this.currentRecognizer.setEnabled(false);
    }, 4000);
  }

  build() {
    Column() {
      Text(`offsetX: ${this.offsetX}`)
        .margin(16);
      Column() {
        // ...
      }
      .margin({ left: 16 })
      .height(200)
      .width(300)
      .border({ width: 3 })
      .id('column')
      .visibility(this.flag ? Visibility.Visible : Visibility.None)
      // 以组件左上角为坐标原点进行移动
      .translate({ x: this.offsetX, y: this.offsetY, z: 0 })
      .onGestureRecognizerJudgeBegin((event: BaseGestureEvent, current: GestureRecognizer,
        others: Array<GestureRecognizer>) => {
        if (current) {
          let target = current.getEventTargetInfo();
          if (target) {
            // 通过组件Id与手势类型找到需要控制的组件识别器
            if (target.getId() === 'column' &&
              current.getType() === GestureControl.GestureType.PAN_GESTURE) {
              // 保存当前组件的识别器
              this.currentRecognizer = current;
            }
          }
        }
        console.info('event-', event, others);
        return GestureJudgeResult.CONTINUE;
      })
      // 左右拖动触发该手势事件
      .gesture(
        PanGesture(this.panOption)
          .onActionStart((event: GestureEvent) => {
            if (event) {
            }
          })
          .onActionUpdate((event: GestureEvent) => {
            if (event) {
              // 实现拖拽效果
              this.offsetX = this.positionX + event.offsetX;
              this.offsetY = this.positionY + event.offsetY;
            }
          })
          .onActionEnd((event: GestureEvent) => {
            if (event) {
              this.positionX = this.offsetX;
              this.positionY = this.offsetY;
            }
          })
      );
    }
    .alignItems(HorizontalAlign.Start);
  }
}

常见FAQ

Q:如何拦截web的手势动作?

A:可以参考手势拦截增强文档中的示例将内层的Scoller容器换成Web即可实现拦截Web手势。