将index、targetIndex输出,观察index和targetIndex的值是否相同,若相同,则说明手指抬起时并没有滑入下一个页面;若不相同,则说明手指抬起时已经滑入了下一个页面。可以根据以下步骤来完成:
示例代码如下所示:
class MyDataSource implements IDataSource { private list: number[] = []; constructor(list: number[]) { this.list = list; } totalCount(): number { return this.list.length; } getData(index: number): number { return this.list[index]; } registerDataChangeListener(): void { } unregisterDataChangeListener() { } } @Entry @Component struct SwiperDemo { private swiperController: SwiperController = new SwiperController(); private data: MyDataSource = new MyDataSource([]); private currentIndex: number = 4; aboutToAppear(): void { let list: number[] = []; for (let i = 0; i <= 10; i++) { list.push(i); } this.data = new MyDataSource(list); } build() { Column({ space: 5 }) { Swiper(this.swiperController) { LazyForEach(this.data, (item: string) => { Text(item.toString()) .width('90%') .height(160) .backgroundColor('#f1f3f5') .textAlign(TextAlign.Center) .fontSize(30); }, (item: string) => item); } .index(this.currentIndex) // 设置当前显示的索引 .loop(false) // 设置是否循环显示。false表示不循环 // 监听当前索引的变化,当滑动到新页面时更新currentIndex .onChange((index: number) => { this.currentIndex = index; }) .onAnimationStart((index: number, targetIndex: number, extraInfo: SwiperAnimationEvent) => { console.info(`index: ${index}`); console.info(`targetIndex: ${targetIndex}`); console.info(`current offset: ${extraInfo.currentOffset}`); console.info(`target offset: ${extraInfo.targetOffset}`); console.info(`velocity: ${extraInfo.velocity}`); }); // 核心是这段代码 Row({ space: 12 }) { Button('showNext') .onClick(() => { this.swiperController.showNext(); }); Button('showPrevious') .onClick(() => { this.swiperController.showPrevious(); }); }.margin(5); }.width('100%') .margin({ top: 5 }); } }
输出结果和效果预览一致。
另外,currentOffset、targetOffset、velocity分别输出了Swiper当前显示元素在主轴方向上,相对于Swiper起始位置的位移、Swiper动画目标元素在主轴方向上,相对于Swiper起始位置的位移以及Swiper离开动画开始时的离开速度。这些数据可以对手势进行更具体的监听。