目录

页面滚动到某个距离后禁止继续向下滚动

问题现象

如何实现当页面滚动到某一个距离时,不能再继续向下滚动。

效果预览

背景知识

解决方案

  1. 为Scroll组件添加onDidScroll方法,该方法在页面滚动过程中实时通过currentOffset获取Scroll的偏移量yOffset。
    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)
    // Scroll滚动时触发该回调
    .onDidScroll(() => {
      this.yOffset = this.scroller.currentOffset().yOffset;
      if (this.yOffset >= 1000) {
        this.scroller.scrollTo({ xOffset: 0, yOffset: 1000, animation: true });
      }
    })
  2. 当yOffset大于等于1000vp时,使用scrollTo方法使页面滑动到指定位置,即可实现页面无法继续向下滑动的效果。
    if (this.yOffset >= 1000) {
      this.scroller.scrollTo({ xOffset: 0, yOffset: 1000, animation: true });
    }

完整代码如下所示:

@Entry
@Component
struct ScrollDemo {
  @State yOffset: number = 0;
  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() {
    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)
      // Scroll滚动时触发该回调
      .onDidScroll(() => {
        this.yOffset = this.scroller.currentOffset().yOffset;
        if (this.yOffset >= 1000) {
          this.scroller.scrollTo({ xOffset: 0, yOffset: 1000, animation: true });
        }
      })
      .scrollBar(BarState.On)
      .scrollBarColor(Color.Gray)
      .scrollBarWidth(2)
      .friction(0.6)
      .edgeEffect(this.yOffset <= 0 ? EdgeEffect.Spring : EdgeEffect.None);
    }
    .width('100%')
    .height('100%')
    .backgroundColor(0xDCDCDC);
  }
}