HarmonyOS 如何实现超过一行自动截取

宽度(根据内容撑开的)不一样Text,假设一行能显示的3.5个Text,想实现让它超过3只展示3个,假设一行能显示的4.x个Text,想实现让它超过4只展示4个在HarmonyOS中是否支持,是否有demo

HarmonyOS
2025-01-09 14:32:18
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
zxjiu

可以通过MeasureUtils的measuretextsize方法,来计算指定文本单行布局下的宽度。然后通过布局预留的宽度来对文本数组进行限制。

api文档:

https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-arkui-uicontext-V5#measuretextsize12

如下是编写的简易demo:

import { MeasureUtils } from '@kit.ArkUI';

@Entry
@Component
struct Indexssss {
  @State uiContext: UIContext = this.getUIContext();
  @State uiContextMeasure: MeasureUtils = this.uiContext.getMeasureUtils();
  @State textFontSize: string = '50px'
  @State textArr: string[] = ['xxx', 'asasaa', 'xxx', 'abbbbb', 'ssssss', 'ssssss', 'ssssss', 'ssssss']
  @State textWidthSum: number = 0;

  aboutToAppear(): void {
    for (let i = 0; i < this.textArr.length; i++) {
      let textSize = this.uiContextMeasure.measureTextSize({
        textContent: this.textArr[i],
        fontSize: this.textFontSize
      })

      this.textWidthSum += textSize.width as number
      console.info(this.textWidthSum + "====" + i)

      if (this.textWidthSum > 400) {
        //第三个超过长度,从第二个开始删,删除8-2个 ,这边i真好对应2
        this.textArr.splice(i, this.textArr.length - i)
        //超出的减去
        this.textWidthSum -= textSize.width as number
        return
      }
    }
  }

  build() {
    Row() {
      Column({ space: 10 }) {
        Row() {
          ForEach(this.textArr, (item: string) => {
            Text(item).fontSize(this.textFontSize).borderWidth(1)
          })
        }

        Text(`The width ': ${this.textWidthSum}`)
      }
      .width('100%')
    }
    .height('100%')
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
分享
微博
QQ
微信
回复
2025-01-09 18:06:40


相关问题
HarmonyOS 如何实现一行四列的列表
636浏览 • 1回复 待解决
HarmonyOS 一行文案不同字体大小
464浏览 • 1回复 待解决