HarmonyOS Tab组件的顶部Tab栏,在设置为可滚动时,无法手动控制滚动位置

Tab组件的顶部栏,当Tab过多,设置为可滚动时,随着内容页面的滚动,Tab标签只有硬切换效果,没有动效,也没有相关控制器支持手动控制滑动。

HarmonyOS
2024-09-24 12:32:34
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
superinsect

参考示例如下:

import display from '@ohos.display';  
import componentUtils from '@ohos.arkui.componentUtils';  
  
@Entry  
@Component  
struct swiperTab {  
  private displayInfo: display.Display | null = null;  
  private animationDuration: number = 300; //动画时间  
  @State swiperIndex: number = 0; //内容区当前Index  
  @State swiperWidth: number = 0; // vp 内容区宽度  
  @State indicatorWidth: number = 0; // vp 页签宽度  
  @State indicatorMarginLeft: number = 5; // vp 当前页签距离左边margin  
  @State indicatorIndex: number = 0; //当前页签Index  
  @State swipeRatio: number = 0; //判断是否翻页,页面滑动超过一半,tabBar切换到下一页。  
  private arr: string[] = ['关注', '推荐', '热点', '上海', '视频', '新时代', '新歌', '新碟', '新片'];  
  private textLength: number[] = [2, 2, 2, 2, 2, 3, 2, 2, 2] // 控制页签所在父容器宽度,避免造成下划线目标位置计算错误  
  private scroller: Scroller = new Scroller();  
  private swiperController: SwiperController = new SwiperController();  
  
  
  aboutToAppear(): void {  
    this.displayInfo = display.getDefaultDisplaySync(); //获取屏幕实例  
  }  
  
  
  // 获取屏幕宽度,单位vp  
  private getDisplayWidth(): number {  
    return this.displayInfo != null ? px2vp(this.displayInfo.width) : 0;  
  }  
  
  
  // 获取组件大小、位置、平移缩放旋转及仿射矩阵属性信息。  
  private getTextInfo(index: number): Record<string, number> {  
    let modePosition: componentUtils.ComponentInfo = componentUtils.getRectangleById(index.toString());  
    try {  
      return { 'left': px2vp(modePosition.windowOffset.x), 'width': px2vp(modePosition.size.width) }  
    } catch (error) {  
      return { 'left': 0, 'width': 0 }  
    }  
  }  
  
  
  // 当前下划线动画  
  private getCurrentIndicatorInfo(index: number, event: SwiperAnimationEvent): Record<string, number> {  
    let nextIndex = index;  
    // 滑动范围限制,Swiper不可循环,Scroll保持不可循环  
    if (index > 0 && event.currentOffset > 0) {  
      nextIndex--; // 左滑  
    } else if (index < this.arr.length - 1 && event.currentOffset < 0) {  
      nextIndex++; // 右滑  
    }  
    // 获取当前tabbar的属性信息  
    let indexInfo = this.getTextInfo(index);  
    // 获取目标tabbar的属性信息  
    let nextIndexInfo = this.getTextInfo(nextIndex);  
    // 滑动页面超过一半时页面切换  
    this.swipeRatio = Math.abs(event.currentOffset / this.swiperWidth);  
    let currentIndex = this.swipeRatio > 0.5 ? nextIndex : index; // 页面滑动超过一半,tabBar切换到下一页。  
    let currentLeft = indexInfo.left + (nextIndexInfo.left - indexInfo.left) * this.swipeRatio;  
    let currentWidth = indexInfo.width + (nextIndexInfo.width - indexInfo.width) * this.swipeRatio;  
    this.indicatorIndex = currentIndex;  
    return { 'index': currentIndex, 'left': currentLeft, 'width': currentWidth };  
  }  
  
  private scrollIntoView(currentIndex: number): void {  
    const indexInfo = this.getTextInfo(currentIndex);  
    let tabPositionLeft = indexInfo.left;  
    let tabWidth = indexInfo.width;  
    // 获取屏幕宽度,单位vp  
    const screenWidth = this.getDisplayWidth();  
    const currentOffsetX: number = this.scroller.currentOffset().xOffset; //当前滚动的偏移量  
  
  
    this.scroller.scrollTo({  
      // 将tabbar定位在正中间  
      xOffset: currentOffsetX + tabPositionLeft - screenWidth / 2 + tabWidth / 2,  
      yOffset: 0,  
      animation: {  
        duration: this.animationDuration,  
        curve: Curve.Linear,  
      }  
    });  
    this.underlineScrollAuto(this.animationDuration, currentIndex);  
  
  }  
  
  
  private startAnimateTo(duration: number, marginLeft: number, width: number): void {  
    animateTo({  
      duration: duration, // 动画时长  
      curve: Curve.Linear, // 动画曲线  
      onFinish: () => {  
        console.info('play end')  
      }  
    }, () => {  
      this.indicatorMarginLeft = marginLeft;  
      this.indicatorWidth = width;  
    })  
  }  
  
  
  // 下划线动画  
  private underlineScrollAuto(duration: number, index: number): void {  
    let indexInfo = this.getTextInfo(index);  
    this.startAnimateTo(duration, indexInfo.left, indexInfo.width);  
  }  
  build() {  
    Column() {  
      //  tabbar  
      Column() {  
        Scroll(this.scroller) {  
          Row() {  
            ForEach(this.arr, (item: string, index: number) => {  
              Column() {  
                Text(item)  
                  .fontSize(16)  
                  .borderRadius(5)  
                  .fontColor(this.indicatorIndex === index ? Color.Red : Color.Black)  
                  .fontWeight(this.indicatorIndex === index ? FontWeight.Bold : FontWeight.Normal)  
                  .margin({ left: 5, right: 5 })  
                  .id(index.toString())  
                  .onAreaChange((oldValue: Area, newValue: Area) => {  
                    if (this.indicatorIndex === index &&  
                      (this.indicatorMarginLeft === 0 || this.indicatorWidth === 0)) {  
                      if (newValue.globalPosition.x != undefined) {  
                        let positionX = Number.parseFloat(newValue.globalPosition.x.toString());  
                        this.indicatorMarginLeft = Number.isNaN(positionX) ? 0 : positionX;  
                      }  
                      let width = Number.parseFloat(newValue.width.toString());  
                      this.indicatorWidth = Number.isNaN(width) ? 0 : width;  
                    }  
                  })  
                  .onClick(() => {  
                    this.indicatorIndex = index;  
                    // 点击tabbar下划线动效  
                    this.underlineScrollAuto(this.animationDuration, index);  
                    this.scrollIntoView(index);  
                    // 跟swiper进行联动  
                    this.swiperIndex = index;  
                  })  
              }  
              .width(this.textLength[index] * 28)  
            }, (item: string) => item)  
          }  
          .blendMode(BlendMode.SRC_IN, BlendApplyType.OFFSCREEN)  
          .backgroundColor(Color.Transparent)  
          .height(32)  
        }  
        // 设置tabbar文字两端显隐  
        .linearGradient({  
          angle: 90,  
          colors: [['rgba(0, 0, 0, 0)', 0], ['rgba(0, 0, 0, 1)', 0], ['rgba(0, 0, 0, 1)', 0.9], ['rgba(0, 0, 0, 0)', 1]]  
        })  
        .blendMode(BlendMode.SRC_OVER, BlendApplyType.OFFSCREEN)  
        .width('100%')  
        .scrollable(ScrollDirection.Horizontal)  
        .scrollBar(BarState.Off)  
        .edgeEffect(EdgeEffect.None)  
        // 滚动事件回调, 返回滚动时水平、竖直方向偏移量  
        .onScroll((xOffset: number, yOffset: number) => {  
          this.indicatorMarginLeft -= xOffset;  
        })  
        // 滚动停止事件回调  
        .onScrollStop(() => {  
          this.underlineScrollAuto(0, this.indicatorIndex);  
        })  
  
        Column()  
          .width(this.indicatorWidth)  
          .height(2)  
          .borderRadius(2)  
          .backgroundColor(Color.Red)  
          .alignSelf(ItemAlign.Start)  
          .margin({ left: this.indicatorMarginLeft, top: 5 })  
      }  
      .width('100%')  
      .margin({ top: 15, bottom: 10 })  
  
      Swiper(this.swiperController) {  
        ForEach(this.arr, (item: string, index: number) => {  
          Column() {  
            Text(item)  
          }  
          .width('100%')  
          .height('100%')  
          .alignItems(HorizontalAlign.Center)  
          .justifyContent(FlexAlign.Center)  
          .backgroundColor($r('sys.color.ohos_id_color_sub_background'))  
          .onAreaChange((oldValue: Area, newValue: Area) => {  
            let width = Number.parseFloat(newValue.width.toString());  
            this.swiperWidth = Number.isNaN(width) ? 0 : width;  
          })  
        }, (item: string) => item)  
      }  
      .onChange((index: number) => {  
        this.swiperIndex = index;  
      })  
      .cachedCount(2)  
      // 跟自定义tabbar进行联动效果  
      .index(this.swiperIndex)  
      .indicator(false)  
      .curve(Curve.Linear)  
      .loop(false)  
      .onAnimationStart((index: number, targetIndex: number, event: SwiperAnimationEvent) => {  
        // 切换动画开始时触发该回调。下划线跟着页面一起滑动,同时宽度渐变。  
        this.indicatorIndex = targetIndex;  
        this.underlineScrollAuto(this.animationDuration, targetIndex);  
      })  
      .onAnimationEnd((index: number, event: SwiperAnimationEvent) => {  
        // 切换动画结束时触发该回调。下划线动画停止。  
        let currentIndicatorInfo = this.getCurrentIndicatorInfo(index, event);  
        this.startAnimateTo(0, currentIndicatorInfo.left, currentIndicatorInfo.width);  
        this.scrollIntoView(index);  
      })  
      .onGestureSwipe((index: number, event: SwiperAnimationEvent) => {  
        // 在页面跟手滑动过程中,逐帧触发该回调。  
        let currentIndicatorInfo = this.getCurrentIndicatorInfo(index, event);  
        this.indicatorIndex = currentIndicatorInfo.index; //当前页签index  
        this.indicatorMarginLeft = currentIndicatorInfo.left; //当前页签距离左边margin  
        this.indicatorWidth = currentIndicatorInfo.width; //当前页签宽度  
      })  
    }  
    .width('100%')  
    .height('100%')  
  }  
}
分享
微博
QQ
微信
回复
2024-09-24 16:02:59
相关问题
HarmonyOS Tabs组件Tab滚动问题
532浏览 • 1回复 待解决
想实现tabBar多个tab滚动
277浏览 • 1回复 待解决
Tab 设置 barBackgroundColor透明不生效
292浏览 • 1回复 待解决
HarmonyOS Tab组件无法响应onPageShow
467浏览 • 1回复 待解决
HarmonyOS使用Web组件如何监听滚动位置
580浏览 • 2回复 待解决
Tab组件无法左对齐该怎么处理?
406浏览 • 1回复 待解决
Web组件怎么知道滚动顶部
845浏览 • 1回复 待解决
Tab导航tabbar子组件突出上沿显示
2242浏览 • 1回复 待解决
HarmonyOS Navigation和Tab组件问题
903浏览 • 1回复 待解决