自动播放
手动拖拽
代码
Swiper封装
/**
* 案例
* 多列循环轮播图
* 处在图像中间的图会有聚焦特效
*/
@Component
export default struct MultiGridScrollingSwiper {
@State focusedIndex: number = 0
@Prop swiperList: object[]
@BuilderParam
buildItem?: (item: object) => void // 构建轮播图的函数
keyGenerator?: (item: object) => string //关键字去重,是Foreach组件需要的函数
build() {
Swiper() {
ForEach(this.swiperList, (item: object, index:number) => {
Row() { //单个元素的容器
if(this.buildItem) {
this.buildItem(item)
}
}
.margin({ top: 10, bottom: 10 }) // ListItem容器设置外边框,为实际item放大所需要的空间
.scale((this.focusedIndex + 1 == index) ?
{ x: 1.2, y: 1.2 } : { x: 1, y: 1 }) //放大效果,使用scale实现
}, this.keyGenerator)
}
.indicator(false) // 取消导航
.autoPlay(true) // 自动播放
.loop(true) // 循环播放
.displayCount(3, false) // 分组数 与 按组滚动
.onAnimationStart((index: number, targetIndex: number, info) => {
this.focusedIndex = targetIndex + 1 < this.swiperList.length ? targetIndex : -1
}) // 滚动动画开始的回调函数 响应速度快
}
}
示例调用
声明自定义组件
MultiGridScrollingSwiper({ swiperList: {这里放你的数组}, buildItem: {元素构造器,传入用@Builder装饰的函数}, keyGenerator?:{自定义组件内Foreach组件所需的去重函数} })
定义元素构造器
@Builder
builderSwiperItem(item:object):void{
//在这里定义你的元素
}
注意
示例中所传递的参数类型都是object,可以根据自己定义的参数类型去改动