我这里是加载一个实体类列表 类似 List 的数据,那么首先写一个dataSource:
export class MyDataSource implements IDataSource {
private list: MyBean[] = []
constructor(list: MyBean[]) {
this.list = list
}
totalCount(): number {
return this.list.length
}
getData(index: number): MyBean{
return this.list[index]
}
registerDataChangeListener(listener: DataChangeListener): void {
}
unregisterDataChangeListener() {
}
}
然后在代码中加入
@Entry
@Component
struct SwiperExample {
private swiperController: SwiperController = new SwiperController()
private data: MyDataSource = new MyDataSource([])
aboutToAppear(): void {
//在DataSource中放入你自己的list数据
let list: MyBean[] = []
for (let i = 1; i <= 10; i++) {
let b = MyBean()
list.push(b);
}
this.data = new MyDataSource(list)
}
build() {
Column() {
Swiper(this.swiperController) {
LazyForEach(this.data, (item: MyBean, index:number) => {
//这里写viewpager中的布局
Text(`${index}`)
})
.indicator(false)
}
}
}
}