HarmonyOS Next应用开发中,如何在 Swiper 中实现自动播放和暂停?

阅读 758
1 个回答

可以使用定时器来实现 Swiper 的自动播放,通过设置一个定时器,在一定时间间隔后切换 Swiper 的索引来实现自动播放效果。当需要暂停时,可以清除定时器。以下是示例代码:

@Entry
@Component
struct SwiperAutoPlay {
  @State swiperIndex: number = 0
  @State isPlaying: boolean = true
  timer: any = null

  startAutoPlay() {
    this.timer = setInterval(() => {
      this.swiperIndex = (this.swiperIndex + 1) % 3; // 假设一共有 3 个页面
    }, 2000); // 每 2 秒切换一次页面
  }

  pauseAutoPlay() {
    clearInterval(this.timer);
    this.isPlaying = false;
  }

  build() {
    Column() {
      Swiper({ index: this.swiperIndex })
       .children([
          Text('Page 1').width('100%').height('100%'),
          Text('Page 2').width('100%').height('100%'),
          Text('Page 3').width('100%').height('100%'),
        ])
      Button(this.isPlaying? '暂停' : '播放').onClick(() => {
        if (this.isPlaying) {
          this.pauseAutoPlay();
        } else {
          this.startAutoPlay();
        }
      })
    }
  }
}

本文参与了 【 HarmonyOS NEXT 技术问答冲榜,等你来战!】欢迎正在阅读的你也加入。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进