HarmonyOS鸿蒙Next中Swiper组件滑动时,无法监听其距离两端的距离如何解决

HarmonyOS鸿蒙Next中Swiper组件滑动时,无法监听其距离两端的距离如何解决

【问题现象】

使用Swiper组件,需要实现滑动超过一定距离时进行相应的操作的功能,当前无法监听滑动到边缘后超过的距离是多少。

【定位思路】

  1. Swiper的onContentDidScroll12方法和onGestureSwipe方法都可以监控滑动。
  2. 要具体监听滑动的距离,需要使用onGestureSwipe。

【背景知识】

使用Swiper的onGestureSwipe方法,可以实现监听滑动的距离以及过程。

Swiper组件属性介绍:

onGestureSwipe(event: (index: number, extraInfo: SwiperAnimationEvent) => void) 在页面跟手滑动过程中,逐帧触发该回调。多列Swiper时,index为最左侧组件的索引。

参数:

参数名 类型 必填 说明
index number 当前显示元素的索引。
extraInfo SwiperAnimationEvent 动画相关信息,只返回主轴方向上当前显示元素相对于Swiper起始位置的位移。

【解决方案】

基于左右滑动实现效果,参考以下代码:

this.getUIContext().getPromptAction().showToast({ message: '> 50' })替换成想要刷新的逻辑:

@Entry
@Component
struct Page240830111844078 {
  private swiperController: SwiperController = new SwiperController()
  private data: MyDataSource = new MyDataSource([])
  private isRefresh: boolean = false
  aboutToAppear(): void {
  }

  build() {
    Column({ space: 5 }) {
      Swiper(this.swiperController) {
        LazyForEach(this.data, (item: string) => {
          Text(item.toString())
          ……
        }, (item: string) => item)
      }
      .cachedCount(2)
      .index(1)
      .autoPlay(false)
      .interval(4000)
      .loop(false)
      .indicatorInteractive(true)
      .duration(1000)
      .itemSpace(0)
      .indicator() // 设置圆点导航点样式
      .displayArrow({}, false) // 设置导航点箭头样式
      .curve(Curve.Linear)
      .onGestureSwipe((index: number, extraInfo: SwiperAnimationEvent) => {
        if (index === 0) {
          if (extraInfo.currentOffset > 50) {
            if (!this.isRefresh) {
              this.isRefresh = true
              this.getUIContext().getPromptAction().showToast({ message: '> 50' })
            }
          } else {
            this.isRefresh = false
          }
        }
        if (index === this.data.totalCount() - 1) {
          if (extraInfo.currentOffset < -50) {
            this.getUIContext().getPromptAction().showToast({ message: '< -50' })
          }
        }
      })
    }.width('100%')
    .margin({ top: 5 })
  }
}

效果如图:

点击放大


更多关于HarmonyOS鸿蒙Next中Swiper组件滑动时,无法监听其距离两端的距离如何解决的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于HarmonyOS鸿蒙Next中Swiper组件滑动时,无法监听其距离两端的距离如何解决的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


使用Swiper组件的onGestureSwipe方法监听滑动距离

通过extraInfo.currentOffset获取当前显示元素相对于Swiper起始位置的位移,判断是否超过设定距离。示例代码中,当currentOffset大于50或小于-50时触发相应操作。

回到顶部