可以使用Text组件控制器的布局管理器对象中的getLineCount方法获取组件内容的总行数,该方法包含了因文本过长导致的换行,能准确获取文本内容行数。
@Entry
@Component
struct Index1 {
private controller: TextController = new TextController();
textStr: string =
'测试文本\n测试文本\n测试文本\n测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本';
@State lineCount: number = 0;
build() {
Column({ space: 20 }) {
Text(this.textStr, { controller: this.controller })
.fontSize(20)
.backgroundColor(Color.White)
.borderRadius('50px')
.padding(16)
.margin({ left: 16, right: 16 });
Text(`该文本总共有${this.lineCount}行`)
.fontColor('#0A59F7');
Button('点击计算')
.onClick(() => {
let layoutManager: LayoutManager = this.controller.getLayoutManager();
let lineCount = layoutManager.getLineCount();
this.lineCount = lineCount;
});
}
.height('100%')
.width('100%')
.justifyContent(FlexAlign.Center)
.backgroundColor('#efefef')
.alignItems(HorizontalAlign.Center);
}
} 效果预览:
