自定义吸顶页面

54 阅读1分钟
/**
 * 滚动吸顶案例
 */
@Entry
@Component
struct Index {
  //1-20数组
  @State list: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
  @State topHeight: number = 0
  @State maxTopHeight: number = 0
  private scroller: Scroller = new Scroller()

  getTopHeight() {
    this.maxTopHeight = this.topHeight + 0 //据顶部距离 + 安全距离
  }

  aboutToAppear(): void {
    let time = setTimeout(() => {
      this.getTopHeight()
      clearTimeout(time)
    }, 300)
  }

  build() {
    Stack({ alignContent: Alignment.TopStart }) {
      //此处可以放图片或其他组件
      Image($r('app.media.background'))
        .width('100%')
        .aspectRatio(375 / 132)
        .onSizeChange((oldValue, newValue) => {
          this.topHeight = Number(newValue.height)
        })
      Scroll(this.scroller) {
        Column() {
          Text(`顶部`)
            .height(40)
            .width('100%')
            .textAlign(TextAlign.Center)
            .backgroundColor('#28db70')
            .margin({ top: this.topHeight })
          List() {
            ForEach(this.list, (item: number, index) => {
              ListItem() {
                Text(`${item}`)
                  .fontSize(50)
              }
              .height(60)
              .width('100%')
            })
            ListItem() {
              
            }
            .width('100%')
            .height(50)
          }
          .edgeEffect(EdgeEffect.None)
          .scrollBar(BarState.Off)
          .nestedScroll({
            scrollForward: NestedScrollMode.PARENT_FIRST,
            scrollBackward: NestedScrollMode.SELF_FIRST
          })
          .backgroundColor(Color.White)
          .height('100%')
          .width('100%')
        }
        .width('100%')
      }
      .height('100%')
      .width('100%')
      .scrollBar(BarState.Off)
      .onScrollFrameBegin((offset: number) => {
        let yOffset = this.scroller.currentOffset().yOffset
        if (yOffset && offset > 0) {
          if (offset + yOffset > this.maxTopHeight) {
            offset = this.maxTopHeight - yOffset
          }
        }
        return { offsetRemain: offset }
      })
    }
    .width('100%')
    .height('100%')
  }
}