本文原创发布在华为开发者社区

介绍

本示例通过设置nestedScroll属性,实现Tab组件的TabBar和List组件吸顶效果。

实现吸顶效果源码链接

效果预览

请添加链接描述

使用说明

卡片数据来自预置用例,可根据实际情况自行修改。同时可以初始化偏移量列表。

实现思路

设置scrollForward的滚动模式为NestedScrollMode.PARENT_FIRST:
当控制Data_List内元素向前滚动时,其父组件Column先滚动,覆盖Scroll组件嵌套的Column组件内的Stack组件(搜索框),随后Column组件触碰顶部边缘,触发边缘效果,从而将Class_List固定在顶部
设置scrollBackward的滚动模式为NestedScrollMode.SELF_FIRST:
当控制Data_List内元素向后滚动时,Data_List的内容先滚动,直至滚动到Data_List最顶部后,父组件Column开始滚动


List() {
  ForEach(this.itemData, (item: number) => {
    ListItem() {
      Text(`${ item }`)
        .height(80)
        .width('100%')
        .textAlign(TextAlign.Center)
        .backgroundColor(0xDDDDDD)
        .margin({bottom: 5})
    }
  })
}.height('90%')
  .nestedScroll({
    scrollForward: NestedScrollMode.PARENT_FIRST,
    scrollBackward: NestedScrollMode.SELF_FIRST
  })

设置scrollForward的滚动模式为NestedScrollMode.PARENT_FIRST:
当控制List内元素向前滚动时,其父组件TabContent先滚动,覆盖Scroll组件嵌套的Column组件内的Image组件,随后Tabs组件触碰顶部边缘,触发边缘效果,从而固定在顶部
设置scrollBackward的滚动模式为NestedScrollMode.SELF_FIRST:
当控制List内元素向后滚动时,List的内容先滚动,直至滚动到List最顶部后,父组件TabContent开始滚动

// 创建Tabs组件单个tab下的内容组件,并设置TabContent组件内的List组件的nestedScroll属性,List组件的父组件为TabContent组件
@Builder
tabContentData(tabTitle: string) {
  TabContent() {
    List() {
      ForEach(this.itemData, (item: number) => {
        ListItem() {
          Text(`${ item }`)
            .height(80)
            .width('100%')
            .textAlign(TextAlign.Center)
            .backgroundColor(0xDDDDDD)
            .margin({bottom: 5})
        }
      })
    }
    .nestedScroll({
      scrollForward: NestedScrollMode.PARENT_FIRST,
      scrollBackward: NestedScrollMode.SELF_FIRST
    })
  }.tabBar(tabTitle)
    .padding({top:5, bottom:5})
    .borderWidth(1)
    .borderColor(Color.Red)
}

鸿蒙场景化代码
1 声望0 粉丝