文档管理中心
|

ArkUI (方舟UI框架)

UI

HarmonyOS 5

HarmonyOS 全文省略展开收起demo (API12+)

HarmonyOS 全文省略展开收起demo (API12+)

点赞
收藏
回复
1
分享
举报
浏览25 发布于2026-04-02 11:25未知归属地
全部评论
最多点赞
最新发布
最早发布
import { inspector } from '@kit.ArkUI';

@Entry
@Component
struct RenderTest {
  @State text: string = 'Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World!'
  @State isEllipsis: boolean = false
  controller: TextController = new TextController()
  maxLine: number = 2
  ellipsisText: string = '...展开'
  textWidth: number = 200

  aboutToAppear(): void {
    const context = this.getUIContext()
    let listener: inspector.ComponentObserver = context.getUIInspector().createComponentObserver('TEXT_DEMO')
    listener.on('layout', () => {
      const manager = this.controller.getLayoutManager()
      const line = manager.getLineCount()
      console.log(`ccc ${line} `)
      if (line <= this.maxLine) {
        return;
      }
      const lastLine = manager.getLineMetrics(this.maxLine - 1)
      const eWidth = context.getMeasureUtils().measureText({ textContent: this.ellipsisText })

      const parentWidth = context.vp2px(this.textWidth)
      let lastIndex = lastLine.endIndex
      for (let i = lastLine.endIndex; i > lastLine.startIndex; i--) {
        const textBox = manager.getRectsForRange({ start: lastLine.startIndex, end: i }, 0, 0)
        let info = textBox[0]
        let width = info.rect.right - info.rect.left
        if (eWidth + width <= parentWidth) {
          lastIndex = i
          break;
        }
      }

      this.text = this.text.slice(0, lastIndex)
      this.isEllipsis = true
    })
  }

  build() {
    Column() {
      Column() {
        Text(undefined, { controller: this.controller }) {
          Span(this.text)
          if (this.isEllipsis) {
            Span(this.ellipsisText)
          }
        }
        .id('TEXT_DEMO')

      }.width(this.textWidth)
      .height(200)
      .backgroundColor(Color.Pink)
    }.width('100%')
    .height('100%')
  }
}
展开全部
1楼回复于2026-04-02 11:25 未知归属地
写回答
新增插入模板功能
一键使用模板,快速填写内容,轻松发帖~
知道了
  • 为了保障您的信息安全,请勿上传您的敏感个人信息(如您的密码等信息)和您的敏感资产信息(如关键源代码、签名私钥、调试安装包、业务日志等信息),且您需自行承担由此产生的信息泄露等安全风险。
  • 如您发布的内容为转载内容,请注明内容来源。

我要提问题

了解社区公约,与您携手共创和谐专业的开发者社区。