鸿蒙掌上驾考宝典应用开发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 核心属性
| 属性 | 值 | 说明 |
|---|---|---|
| cachedCount | 0 | 预加载页面数(0 表示不预加载) |
| index | number | 当前显示的页面索引 |
| loop | false | 是否循环播放 |
| indicator | false | 是否显示导航点指示器 |
| onChange | callback | 页面切换时的回调 |
三、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 联动
更多推荐



所有评论(0)