以下是通过friction与onScrollFrameBegin限制滑动偏移量的实现方案:
@Entry
@Component
struct ScrollerPage1 {
scroller: Scroller = new Scroller();
private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
build() {
Column() {
List({ space: 20, initialIndex: 0, scroller: this.scroller }) {
ForEach(this.arr, (item: number) => {
ListItem() {
Text('' + item)
.width('100%')
.height(100)
.fontSize(16)
.textAlign(TextAlign.Center)
.borderRadius(10)
.backgroundColor(0xFFFFFF);
};
}, (item: number) => item.toString());
}
.listDirection(Axis.Vertical)
.scrollBar(BarState.Off)
.friction(3)
.divider({
strokeWidth: 2,
color: 0xFFFFFF,
startMargin: 20,
endMargin: 20
})
.width('90%');
}
.width('100%')
.height('100%')
.backgroundColor(0xDCDCDC)
.padding({ top: 5 });
}
} 或者设置onScrollFrameBegin:
@Entry
@Component
struct ScrollerPage2 {
scroller: Scroller = new Scroller();
private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
build() {
Column() {
List({ space: 20, initialIndex: 0, scroller: this.scroller }) {
ForEach(this.arr, (item: number) => {
ListItem() {
Text('' + item)
.width('100%')
.height(100)
.fontSize(16)
.textAlign(TextAlign.Center)
.borderRadius(10)
.backgroundColor(0xFFFFFF);
};
}, (item: number) => item.toString());
}
.listDirection(Axis.Vertical)
.scrollBar(BarState.Off)
.divider({
strokeWidth: 2,
color: 0xFFFFFF,
startMargin: 20,
endMargin: 20
})
.width('90%')
.onScrollFrameBegin((offset: number) => {
if (offset > 5) {
offset = 5;
}
if (offset < -5) {
offset = -5;
}
return { offsetRemain: offset };
});
}
.width('100%')
.height('100%')
.backgroundColor(0xDCDCDC)
.padding({ top: 5 });
}
}