往期鸿蒙全套实战文章必看:(附带鸿蒙全栈学习资料)
如何实现Scroll、List单边回弹效果
1. Scroll组件:在onDidScroll里获取currentOffset().yOffset来控制单边回弹效果;
2. List组件:可以在onDidScroll里获取currentOffset().yOffset来控制,还可以通过onScrollIndex实现单边回弹效果。
参考代码如下:
// Scroll组件单边回弹效果
@Entry
@Component
struct ScrollSideRebound {
@State yOffset: number = 0;
scroller: Scroller = new Scroller();
private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
build() {
Stack({ alignContent: Alignment.TopStart }) {
Scroll(this.scroller) {
Column() {
ForEach(this.arr, (item: number) => {
Text(item.toString())
.width('90%')
.height(150)
.backgroundColor(0xFFFFFF)
.borderRadius(15)
.fontSize(16)
.textAlign(TextAlign.Center)
.margin({ top: 10 })
}, (item: string) => item)
}
.width('100%')
}
.scrollable(ScrollDirection.Vertical) // 滚动方向纵向
.scrollBar(BarState.On) // 滚动条常驻显示
.scrollBarColor(Color.Gray) // 滚动条颜色
.scrollBarWidth(2) // 滚动条宽度
.friction(0.6)
.edgeEffect(this.yOffset <= 0 ? EdgeEffect.Spring : EdgeEffect.None) // 滚动到边沿后回弹
.onDidScroll(() => {
this.yOffset = this.scroller.currentOffset().yOffset;
})
}
.width('100%')
.height('100%')
.backgroundColor(0xDCDCDC)
}
}
// List组件单边回弹效果
@Entry
@Component
struct ListSideRebound {
@State isTop: boolean = true;
private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
build() {
Column() {
List({ space: 20, initialIndex: 0 }) {
ForEach(this.arr, (item: number) => {
ListItem() {
Text('' + item)
.width('100%')
.height(100)
.fontSize(16)
.textAlign(TextAlign.Center)
.borderRadius(10)
.backgroundColor(0xFFFFFF)
}
}, (item: string) => item)
}
.listDirection(Axis.Vertical) // 排列方向
.scrollBar(BarState.Off)
.friction(0.6)
.edgeEffect(this.isTop ? EdgeEffect.Spring : EdgeEffect.None)
.onScrollIndex((firstIndex: number) => {
if (firstIndex === 0) {
this.isTop = true;
} else {
this.isTop = false;
}
})
.width('90%')
}
.width('100%')
.height('100%')
.backgroundColor(0xDCDCDC)
.padding({ top: 5 })
}
}