鸿蒙掌上驾考宝典应用开发11:Swiper 轮播组件——从驾考题库切换看滑动容器

发布时间:2026/7/31 16:04:19

鸿蒙掌上驾考宝典应用开发11:Swiper 轮播组件——从驾考题库切换看滑动容器 第11篇Swiper 轮播组件——从驾考题库切换看滑动容器一、引言Swiper 是鸿蒙 ArkUI 中用于实现轮播切换的容器组件支持左右滑动切换页面。DriverLicenseExam 项目在科目切换场景中使用了 Swiper 组件实现了科目一/二/三/四内容的滑动切换。本文将详细解析 Swiper 组件的使用。二、Swiper 基本用法2.1 科目切换的实现在 HomeView 中Swiper 与 Tab 联动实现科目内容的切换// products/entry/src/main/ets/pages/home/HomeView.ets ComponentV2 export struct HomeView { swiperController: SwiperController new SwiperController(); Local currentTab: number 0; Builder tab() { Row() { ForEach(KEMUTAB_LIST, (item: KEMUTabListItem, index: number) { Column() { Text(item.label) .fontColor(this.currentTab index ? $r(sys.color.font_primary) : $r(sys.color.font_secondary)) .fontSize(14) .fontWeight(this.currentTab index ? FontWeight.Bold : FontWeight.Normal); if (this.currentTab index) { Divider().color($r(sys.color.comp_divider)).strokeWidth(2); } } .onClick(() { this.swiperController.changeIndex(index); // Tab 点击时切换 Swiper this.tabChange(index); }); }); } } build() { // ... 其他内容 Swiper(this.swiperController) { this.subjectOneAndFour() // 科目一内容 this.subjectTwoAndThree() // 科目二内容 this.subjectTwoAndThree() // 科目三内容 this.subjectOneAndFour() // 科目四内容 } .cachedCount(0) // 不缓存页面 .index(this.currentTab) // 初始化索引 .loop(false) // 禁止循环 .indicator(false) // 隐藏指示器 .onChange((targetIndex: number) { this.currentTab targetIndex; // 滑动时同步 Tab 状态 }); } }2.2 Swiper 核心属性属性值说明cachedCount0预加载页面数0 表示不预加载indexnumber当前显示的页面索引loopfalse是否循环播放indicatorfalse是否显示导航点指示器onChangecallback页面切换时的回调三、Swiper 与 Tab 的联动机制3.1 双向同步// Tab 点击 → Swiper 切换 tab.onClick(() { this.swiperController.changeIndex(index); this.tabChange(index); }); // Swiper 滑动 → Tab 高亮 Swiper.onChange((targetIndex: number) { this.currentTab targetIndex; });3.2 SwiperController 控制swiperController: SwiperController new SwiperController(); // 编程式切换 swiperController.changeIndex(2); // 切换到指定索引 swiperController.showNext(); // 下一页 swiperController.showPrevious(); // 上一页 swiperController.finishAnimation(); // 立即完成当前动画四、性能优化策略4.1 cachedCount 的权衡// 场景1不缓存适合页面内容较少的场景 Swiper() .cachedCount(0) // 只渲染当前页面 // 场景2预缓存适合页面内容较多的场景 Swiper() .cachedCount(2) // 预渲染前后各 2 页4.2 内容复用同一 Builder 函数可被多次复用减少代码重复// 科目二和科目三共用相同的内容模板 Swiper(this.swiperController) { this.subjectOneAndFour() // 科目一 this.subjectTwoAndThree() // 科目二复用 this.subjectTwoAndThree() // 科目三复用 this.subjectOneAndFour() // 科目四 }五、总结Swiper 组件是实现滑动切换场景的核心容器配合 Tab 组件可以实现常见的Tab 切换 内容滑动交互模式。合理使用 cachedCount 属性可以在性能和体验之间取得平衡。关键源码文件products/entry/src/main/ets/pages/home/HomeView.ets— Swiper Tab 联动

相关新闻