@Entry
@Component
struct Index {
@State cardChangeAnimationDuration: number = 0
swiperController: SwiperController = new SwiperController()
@State autoPlay: boolean = true
userScrolled: boolean = false
dataList: Color[] = [Color.Red, Color.Yellow, Color.Blue]
aboutToAppear(): void {
setInterval(() => {
if (this.autoPlay) {
this.swiperController.showNext()
promptAction.showToast({ message: '切换下一个卡片' })
}
}, 2000);
}
build() {
Stack() {
Swiper(this.swiperController) {
ForEach(this.dataList, (item: Color, index) => {
Text(`卡片${index}`)
.textAlign(TextAlign.Center)
.font({ size: 17, weight: 500 })
.backgroundColor(item)
.opacity(0.5)
})
}
.autoPlay(false) // 组件不自动轮播,自动轮播逻辑交由VM调用scrollToIndex/showNext实现
.loop(this.autoPlay)
.indicator(false)
.duration(this.cardChangeAnimationDuration) // 切换时长可配置
.curve(Curve.Linear) // 注:<=API12, duration生效需要配置.curve(Curve.Linear)
.cachedCount(3)
.width('100%')
.height('100%')
.nestedScroll(SwiperNestedScrollMode.SELF_FIRST)
.onClick(() => {
this.cardChangeAnimationDuration = !this.autoPlay ? 700 : 400
this.autoPlay = !this.autoPlay
if (this.autoPlay) {
this.userScrolled = false
}
})
.onGestureSwipe((index: number, extraInfo: SwiperAnimationEvent) => {
this.userScrolled = true
})
.onAnimationEnd((index: number, extraInfo: SwiperAnimationEvent) => {
if (extraInfo.currentOffset == 0 && this.userScrolled) {
this.autoPlay = false
}
})
.customContentTransition({
timeout: 1000,
transition: (proxy: SwiperContentTransitionProxy) => {
}
})
}
}
}
自定义动画需要自己在实现customContentTransition这个时,自己处理相关得逻辑,请参考示例4https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-container-swiper-V5\#swipercontentanimatedtransition12%E5%AF%B9%E8%B1%A1%E8%AF%B4%E6%98%8E