HarmonyOS应用开发实战:猫猫大作战-Swiper 的声明式用法、控制器操作、引导页完整实现以及与应用启动流程的结合

📅 2026/7/28 12:26:44
HarmonyOS应用开发实战:猫猫大作战-Swiper 的声明式用法、控制器操作、引导页完整实现以及与应用启动流程的结合
前言在应用首次启动时新手引导页通过轮播展示应用的核心功能帮助用户快速上手。HarmonyOS 的Swiper组件提供了声明式的轮播容器支持循环滑动、自动播放、自定义指示器、切换动画等能力。本文以「猫猫大作战」的新手引导页为锚点讲解 Swiper 的声明式用法、控制器操作、引导页完整实现以及与应用启动流程的结合。提示本系列不讲 ArkTS 基础语法与环境搭建假设你已跟完第 1–90 篇。本篇是阶段三第 91 篇。一、Swiper 基本结构1.1 最简轮播Swiper() { Text(第 1 页).fontSize(30) Text(第 2 页).fontSize(30) Text(第 3 页).fontSize(30) }1.2 核心属性属性说明index当前索引双向绑定autoPlay是否自动播放interval自动播放间隔loop是否循环vertical是否垂直滑动indicator指示器样式duration切换动画时长二、新手引导页实现2.1 引导页完整代码Entry Component struct GuidePage { State currentIndex: number 0; private swiperController: SwiperController new SwiperController(); private guides: GuideItem[] [ { emoji: , title: 合并猫咪, desc: 将相同的猫咪拖到一起合并升级, color: #E8F4F8 }, { emoji: , title: 策略消除, desc: 合理安排猫咪位置获得高分, color: #FEF9E7 }, { emoji: , title: 挑战好友, desc: 与好友一较高下登上榜首, color: #FDEBD0 } ]; build() { Column() { Swiper(this.swiperController) { ForEach(this.guides, (item: GuideItem) { this.GuidePage(item) }) } .index(this.currentIndex) .loop(false) // 引导页不循环 .indicator(this.IndicatorStyle()) .onChange((index) { this.currentIndex index }) Button(this.currentIndex this.guides.length - 1 ? 下一步 : 开始使用) .onClick(() { if (this.currentIndex this.guides.length - 1) { this.swiperController.showNext() } else { router.replaceUrl({ url: pages/Index }) } }) } } Builder GuidePage(item: GuideItem) { Column() { Text(item.emoji).fontSize(80) Text(item.title).fontSize(24).fontWeight(FontWeight.Bold).margin({ top: 24 }) Text(item.desc).fontSize(16).fontColor(#666).margin({ top: 12 }) } .width(100%) .height(100%) .backgroundColor(item.color) .justifyContent(FlexAlign.Center) } Builder IndicatorStyle() { DotIndicator() .itemWidth(8).itemHeight(8) .selectedItemWidth(24).selectedItemHeight(8) .color(#CCC).selectedColor(#2ECC71) } } interface GuideItem { emoji: string; title: string; desc: string; color: string; }三、SwiperControllerprivate swiperController: SwiperController new SwiperController(); // 跳转到下一页 this.swiperController.showNext(); // 跳转到上一页 this.swiperController.showPrevious(); // 跳转到指定页 this.swiperController.finishAnimation(this.currentIndex); this.swiperController.showNext();四、总结Swiper 是 HarmonyOS 的轮播容器组件通过SwiperController编程控制翻页配合DotIndicator实现引导页指示器。核心要点Swiper 声明式轮播支持循环、自动播放、自定义指示器SwiperController.showNext/showPrevious 编程控制翻页引导页完成后使用 router.replaceUrl 跳转到主页面下一篇预告第 92 篇将深入 DotIndicator——圆点指示器的样式自定义。如果这篇文章对你有帮助欢迎点赞、收藏⭐、关注你的支持是我持续创作的动力相关资源Swiper 组件参考DotIndicator 参考SwiperController API开源鸿蒙跨平台社区第 90 篇TabContent第 92 篇DotIndicator