如何判断Text组件填充文本后的行数?

我们有个场景需要根据文本行数显示不同的结果,如:

1,低于四行正常显示

2,高于四行需要再第四行的某处(非最后,非中间)进行折断,使用…代替显示后面内容,同时显示“展开按钮”

3,按钮点击,全部显示。

4,全部显示时点击按钮,再折行显示。

阅读 616
1 个回答

解决方案

请参考如下demo:

import measure from '@ohos.measure'

@Entry
@Component
struct TextCollapseTest {
  @State rawTitle: string = "测试测试测试测试是测试测试测试测试测试测试测试测试是测试测试测试测试是测试测试测试测试测试测试测试测试测试测试测试测试测试。"
  @State title: string = this.rawTitle
  @State suffixStr: string = ""
  expanded: Boolean = true
  titleWidth: number = 350
  needProcess: boolean = true
  ellipsis: string = "..."
  EXPAND_STR: string = "展开"
  COLLAPSE_STR: string = "收起"
  MAX_LINES: number = 2;

  aboutToAppear(): void {
    this.process();
  }

  process(): void {
    if (this.expanded) {
      this.collapseText();
    } else {
      this.expandText();
    }
  }

  //展开文本
  expandText(): void {
    console.log('testTag: ' + this.needProcess);
    if (this.needProcess) {
      this.suffixStr = this.COLLAPSE_STR;
      this.expanded = true;
      this.title = this.rawTitle;
    }
  }

  //收起文本
  collapseText(): void {
    if (!this.needProcess) {
      return;
    }
    let titleSize: SizeOptions = measure.measureTextSize({
      textContent: this.rawTitle,
      constraintWidth: this.titleWidth,
      fontSize: 30
    })
    let twoLineSize: SizeOptions = measure.measureTextSize({
      textContent: this.rawTitle,
      constraintWidth: this.titleWidth,
      fontSize: 30,
      maxLines: this.MAX_LINES
    })
    //文本未超过限制行数,不进行展开、收起处理
    if ((titleSize.height as number) == (twoLineSize.height as number)) {
      this.needProcess = false;
      return;
    }

    console.log('test row height:' + titleSize.height)
    console.log('test twoLineSize height:' + twoLineSize.height)

    let clipTitle: string = this.rawTitle
    this.suffixStr = this.EXPAND_STR;
    while ((titleSize.height as number) > (twoLineSize.height as number)) {
      this.expanded = true;
      // 可以修改其他计算算法提高性能
      clipTitle = clipTitle.substring(0, clipTitle.length - 1);
      titleSize = measure.measureTextSize({
        textContent: clipTitle + this.ellipsis + this.suffixStr,
        constraintWidth: this.titleWidth,
        fontSize: 30
      })
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进