鸿蒙使用Swiper实现应用引导页,滑动到最后再滑一次进入主界面

241 阅读2分钟

在鸿蒙ArkUI中,实现Swiper滑动到最后一页后继续滑动跳转其他页面,可以通过以下步骤实现:

一、核心思路

  1. 监听手势滑动事件
    Swiper在页面跟手滑动过程中,会逐帧触发onGestureSwipe回调。该回调会返回当前显示元素的索引以及相关位移信息。
  2. 判断触发条件
    根据onGestureSwipe中返回的索引以及互动姿势判断是否满足触发条件
  3. 触发页面跳转
    当滑动到最后一页且继续滑动时,调用router.pushUrlrouter.replaceUrl实现跳转

二、实现步骤

1. 设置 Swiper 组件

Swiper() {
  ForEach(this.dataArray, (item: DataType, index: number) => {
    Image(item.imageUrl)
      .width('100%')
      .height('100%')
  })
}
.autoPlay(false)          // 关闭自动轮播
.loop(false)              // 关闭循环模式
.onGestureSwipe((index: number, extraInfo: SwiperAnimationEvent) => {
    if (index == this.dataArray.length - 1) {    
        if (extraInfo.currentOffset < -80) {
            this.handleSwipeEnd()
        }
    }
})

2. 跳转

private handleSwipeEnd() {
    // 跳转到目标页面(例如主页)
    router.pushUrl({
      url: 'pages/HomePage'
    })
}

三、完整示例代码

@Entry
@Component
struct SwiperDemo {

  private dataArray: string[] = ['page1', 'page2', 'page3'] // 示例数据

  build() {
    Column() {
      Swiper() {
        ForEach(this.dataArray, (item: string, index: number) => {
          Column() {
            Text(item)
              .fontSize(30)
              .margin({ bottom: 20 })
            Text(index === this.dataArray.length - 1 ? '滑动跳转' : '继续滑动')
          }
          .width('100%')
          .height('100%')
          .backgroundColor(Color.Gray)
        })
      }
      .autoPlay(false)
      .loop(false)
      .onGestureSwipe((index: number, extraInfo: SwiperAnimationEvent) => {
            if (index == this.dataArray.length - 1) {    
                if (extraInfo.currentOffset < -80) {
                this.handleSwipeEnd()
                }
               }
        })     
    }
    .width('100%')
    .height('100%')
  }

  private handleSwipeEnd() {  
      router.pushUrl({
        url: 'pages/HomePage',
        params: { from: 'swiper' }   
        })    
  }
}

四、关键点说明

  1. 关闭循环模式
    .loop(false)确保滑动到最后一页后不会循环回第一页 4 7

  2. 跳转方法选择

    • router.pushUrl():保留当前页,可返回(适合引导页跳主页)7 8
    • router.replaceUrl():替换当前页,不可返回(适合登录页跳主页)7 8
  3. 手势方向判断
    若需区分左右滑动方向,可在onGestureSwipe中通过extraInfo.currentOffset判断滑动偏移量。


五、扩展优化

  1. 添加滑动提示
    在最后一页显示文字或箭头提示用户继续滑动跳转。
  2. 动画过渡
    结合animateTo方法实现平滑跳转动画 4
  3. 参数传递
    通过params属性向目标页面传递数据(如来源标识)7

通过上述方法,可以灵活实现Swiper滑动到最后一页后的跳转逻辑,适用于引导页、轮播图等场景。