鸿蒙ArkTS中实现Sticky效果

需求

在开发中,使用滚动组件时,有时需要实现吸顶(Sticky)效果。在当前ArkTS中没有相应组件,所以我把我的实现代码分享出来

实现原理

结构【Stack组件】>【Scroll组件(吸顶组件占位)】+【吸顶目标Column】

在Scroll滚动时,记录当前总滚动值,并改变吸顶组件的外边距。当吸顶组件出滚动区域时,不再改变外边距即可

期望效果

吸顶效果

代码实现

@Entry
@ComponentV2
export struct Sticky {
  searchHeight = 35
  scroll0Height = 35 //吸顶组件上部分高度
  stickyHeight = 35 //吸顶组件高度
  scrollHeight = 500//模拟数据高度
  @Local currYOffset: number = 0//当前Scroll竖向偏移量
  scroller: Scroller = new Scroller()

  aboutToAppear(): void {
    this.scroller.scrollTo({ xOffset: 0, yOffset: this.currYOffset })
  }

  build() {
    Column() {
      Column() {
        Text("[搜索框区域]")
      }
      .width('100%')
      .height(this.searchHeight )
      .backgroundColor("#999")

      Stack() {
        //滚动区
        Scroll(this.scroller) {
          Column() {
            Column() {
              Text("功能模块")
            }
            .width('100%')
            .height(this.scroll0Height)
            .backgroundColor('#999')

            //吸顶组件占位
            Column()
              .height(this.stickyHeight)

            Column()
              .width('100%')
              .height(this.scrollHeight)
              .backgroundColor('#89a')
            Column()
              .width('100%')
              .height(this.scrollHeight)
              .backgroundColor('#9ab')
            Column()
              .width('100%')
              .height(this.scrollHeight)
              .backgroundColor('#abc')
          }
          .width('100%')
        }
        .width('100%')
        .height('100%')
        .edgeEffect(EdgeEffect.Spring)
        .scrollable(ScrollDirection.Vertical)
        .onWillScroll((x, y) => {
          this.currYOffset += y
        })

        //筛选栏
        Column() {
          Text("筛选栏")
        }
        .width('100%')
        .height(this.stickyHeight)
        .backgroundColor('#700')
        .margin({
          top: this.scroll0Height - Math.min(this.currYOffset, this.scroll0Height)
        })

      }
      .width('100%')
      .layoutWeight(1)
      .alignContent(Alignment.Top)
    }
    .width('100%')
    .height('100%')

  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值