鸿蒙实现吸顶效果的方式

本文详细介绍了如何在DevEcoStudio中使用`Tabs`组件,通过`barPosition`属性设置为`Start`并配合`nestedScroll`处理滚动事件,确保了Tab在滚动时始终保持顶部。作者提供了实际的代码示例来展示这一实现过程。
摘要由CSDN通过智能技术生成

前言:

DevEcoStudio版本:

"compileSdkVersion": 10

效果:

 

原理分析:

        基于Tabs的barPosition属性,设置Tabs的页签位置:BarPosition.Start。这样就能保证在滚动的时候tab位于顶部。因为本身布局是Scroll嵌套List所以需要对滚动事件进行处理。通过List的nestedScroll属性(API 10的属性)设置向前向后两个方向上的嵌套滚动模式。

当向上滑动时:Scroll滑动,List不滑动,当Tabs吸顶后List在滑动。

当向下滑动时:List不在顶部,List滑动,Scroll不滑动,List滑动到顶部后Scroll再滑动。

List(){
   //......
}
.nestedScroll({
   scrollForward: NestedScrollMode.PARENT_FIRST,
   scrollBackward: NestedScrollMode.SELF_FIRST
})

详细代码:

@Entry
@Component
struct Index {
   @State list: number[] = []

   aboutToAppear() {//添加测试数据
      for (let i = 0; i < 30; i++) {
         this.list.push(i)
      }
   }

   @Styles
   listStyle() {
      .backgroundColor(Color.White)
      .height(72)
      .width("100%")
      .borderRadius(12)
   }

   @Builder
   TabBuilder(title: string) {
      Column() {
         Text(title)
            .fontSize(20)
            .fontColor(Color.White)
      }
      .padding({ top: 10, bottom: 10 })
      .justifyContent(FlexAlign.Center)
      .backgroundColor(Color.Pink)
      .height(56)
      .width('100%')
   }

   build() {
      Scroll() {
         Column() {
            Text("头部滚动区域")
               .width("100%")
               .height("30%")
               .fontSize(20)
               .fontColor(Color.White)
               .backgroundColor('#0080DC')
               .textAlign(TextAlign.Center)

            Tabs() {
               TabContent() {
                  List({ space: 10 }) {
                     ForEach(this.list, (item: number) => {
                        ListItem() {
                           Text("item" + item).fontSize(16)
                        }.listStyle()
                     }, (item: string) => item)
                  }.width("100%")
                  .height('100%')
                  .edgeEffect(EdgeEffect.None)
                  .nestedScroll({
                     scrollForward: NestedScrollMode.PARENT_FIRST,
                     scrollBackward: NestedScrollMode.SELF_FIRST
                  })
               }.tabBar(this.TabBuilder("我是吸顶布局"))
            }
            .vertical(false)
            .height("100%")
         }.width("100%")
      }
      .edgeEffect(EdgeEffect.None)
      .backgroundColor('#DCDCDC')
      .scrollBar(BarState.Off)
      .width('100%')
      .height('100%')
   }
}

评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

等风起了

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值