HarmonyOS鸿蒙Next中Swiper如何控制在最边缘时弹性距离

HarmonyOS鸿蒙Next中Swiper如何控制在最边缘时弹性距离

【问题现象】

使用Swiper展示内容时,在列表的第一个和最后一个展示时,可以通过上划或者下划触发弹性伸缩。但是,弹性伸缩的距离过长。是否可以设置Swiper中弹性伸缩的高度,如下图拉到最下面伸缩的距离大概有2/5:

点击放大

把第一个内容拉倒最下面伸缩距离固定:

点击放大

【背景知识】

Swiper相关内容可以参考官方文档Swiper API。官方文档中没有现成的接口设置边缘回弹距离,需要在原有接口的基础上进行一些更改。

【解决方案】

通过禁用Swiper内置的边缘回弹效果,自定义边缘的回弹动作。参考如下代码:

Swiper(this.swiperController) {
  Text() // 轮播内容
    .translate({
      x: this.traX,
      y: this.traY   // 偏移设置为捕获到的偏移量
    })
}
.effectMode(EdgeEffect.None) // 禁用内置边缘效果
.parallelGesture(
  PanGesture({ direction: PanDirection.Vertical })
    .onActionUpdate((event) => {
      // 这里控制滑动距离,第一个往下滑
      if (this.index == 0 && event.offsetY < 50) {
        this.traY = event.offsetY
      }
      // 这里控制滑动距离, 最后一个往上滑
      if (this.index == this.data.totalCount() - 1 && event.offsetY > -50) {
        this.traY = event.offsetY
      }
    })
    .onActionEnd((event) => {
      console.info(JSON.stringify(event))
      animateTo({
        duration: 100, // 这里可以控制回弹速度
        curve: Curve.EaseOut,
        iterations: 1,
        playMode: PlayMode.Normal,
        onFinish: () => {
          console.info('play end')
        }
      }, () => {
        this.traY = 0
      })
    })
)

运行结果:

点击放大

【总结】

对于系统接口行为与预期不符的情况,可以禁用系统接口的默认功能,并重写相关接口以实现预期效果。


更多关于HarmonyOS鸿蒙Next中Swiper如何控制在最边缘时弹性距离的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于HarmonyOS鸿蒙Next中Swiper如何控制在最边缘时弹性距离的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,可以通过禁用Swiper内置的边缘回弹效果,并自定义边缘的回弹动作来控制弹性距离。具体实现如下:

  1. 使用effectMode(EdgeEffect.None)禁用内置边缘效果。
  2. 使用PanGesture捕获滑动事件,并在onActionUpdate中控制滑动距离。
  3. onActionEnd中使用animateTo实现回弹效果。

示例代码:

Swiper(this.swiperController) {
  Text() // 轮播内容
    .translate({
      x: this.traX,
      y: this.traY   // 偏移设置为捕获到的偏移量
    })
}
.effectMode(EdgeEffect.None) // 禁用内置边缘效果
.parallelGesture(
  PanGesture({ direction: PanDirection.Vertical })
    .onActionUpdate((event) => {
      // 这里控制滑动距离,第一个往下滑
      if (this.index == 0 && event.offsetY < 50) {
        this.traY = event.offsetY
      }
      // 这里控制滑动距离, 最后一个往上滑
      if (this.index == this.data.totalCount() - 1 && event.offsetY > -50) {
        this.traY = event.offsetY
      }
    })
    .onActionEnd((event) => {
      animateTo({
        duration: 100, // 这里可以控制回弹速度
        curve: Curve.EaseOut,
        iterations: 1,
        playMode: PlayMode.Normal,
        onFinish: () => {
          console.info('play end')
        }
      }, () => {
        this.traY = 0
      })
    })
)

通过以上方法,可以自定义Swiper在边缘时的弹性距离。

回到顶部