通过 Scroller 的 scrollEdge 方法,我们可以让 List 滚动到顶部,或者底部。
declare class Scroller {
/**
* 回调顶部/底部
*/
scrollEdge(value: Edge);
}
Edge 一共有 4 个值:
declare enum Edge {
Top,
Bottom,
Start,
End
}
接下来,我们写一个回到顶部的示例。
首先,定义数据源并填充数据。
@Entry
@Component
struct Index {
/**
* 数据源
*/
names: string[] = []
aboutToAppear() {
// 填充数据
for (let i = 0; i < 50; i ) {
this.names.push(`数据${i}`)
}
}
}
然后,给 List 设置 Scroller。
@Entry
@Component
struct Index {
/**
* 数据源
*/
names: string[] = []
/**
* 滚动控制器
*/
scroller: Scroller = new Scroller()
aboutToAppear() {
// 填充数据
for (let i = 0; i < 50; i ) {
this.names.push(`数据${i}`)
}
}
build() {
List({ scroller: this.scroller }) {
}
.width('100%')
.height('100%')
}
}
最后,渲染数据,并给 ListItem 添加点击事件,在点击事件里调用 scrollEdge 方法,传入 Edge.Top 回到 List 列表的顶部。
@Entry
@Component
struct Index {
/**
* 数据源
*/
names: string[] = []
/**
* 滚动控制器
*/
scroller: Scroller = new Scroller()
aboutToAppear() {
// 填充数据
for (let i = 0; i < 50; i ) {
this.names.push(`数据${i}`)
}
}
build() {
List({ scroller: this.scroller }) {
ForEach(this.names, (item: string, index: number) => {
ListItem() {
Row() {
Text(item)
.fontSize(30)
}
.width('100%')
.height(100)
.backgroundColor(index % 2 === 0 ? Color.Gray : Color.White)
}
.onClick(() => {
// 回到顶部
this.scroller.scrollEdge(Edge.Top)
})
}, (item: string) => item)
}
.width('100%')
.height('100%')
}
}
运行结果:
从运行结果来看,我们先是向下滑动几次,然后点击 ListItem 回到 List 的顶部位置。
scrollEdge 方法不能设置滚动动画,所以滚动效果比较生硬。
Copyright © 2024 妖气游戏网 www.17u1u.com All Rights Reserved