如何判断在设置maxlines后,当前Text有没有被换行

如何判断在设置maxlines后,当前Text有没有被换行。

HarmonyOS
2024-06-11 23:35:28
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
liqi399

为目标文本设置对照文本,通过measureTextSize设置最大行数(对比文本比目标文本大),然后对比两组的高度,如果目标文本的高度小,则表示被截断。

参考代码:

import measure from '@ohos.measure' 
 
@Entry 
@Component 
struct TextInputDemo { 
  @State text: string = '' 
  @State truncatedHint: string = "文本未截断" 
  controller: TextInputController = new TextInputController() 
 
  build() { 
    Column() { 
      TextInput({ text: this.text, placeholder: 'input your word...', controller: this.controller }) 
        .placeholderColor(Color.Grey) 
        .placeholderFont({ size: 14, weight: 400 }) 
        .caretColor(Color.Blue) 
        .width(400) 
        .height(40) 
        .margin(20) 
        .fontSize(14) 
        .fontColor(Color.Black) 
        .onChange((value: string) => { 
          this.text = value 
          let textSizeShow1 : SizeOptions = measure.measureTextSize({ 
            textContent: this.text, 
            constraintWidth: 100, 
            fontSize: 14, 
            overflow: TextOverflow.Ellipsis, 
            maxLines: 2 
          }) 
          let textSizeShow2 : SizeOptions = measure.measureTextSize({ 
            textContent: this.text + " ", 
            constraintWidth: 100, 
            fontSize: 14, 
            overflow: TextOverflow.Ellipsis, 
            maxLines: 2000000 
          }) 
          console.log("textSizeShow1.height="+ textSizeShow1.height); 
          console.log("textSizeShow2.height="+ textSizeShow2.height); 
 
          if (textSizeShow2 && textSizeShow1 && textSizeShow2?.height && textSizeShow1?.height && (textSizeShow2?.height > textSizeShow1?.height)) { 
            console.log("文本截断") 
            this.truncatedHint =  "文本截断" 
          } else { 
            console.log("文本未截断") 
            this.truncatedHint =  "文本未截断" 
          } 
        }) 
      Text(this.text) 
        .maxLines(2) 
        .width(100) 
        .textOverflow({overflow: TextOverflow.Ellipsis}) 
        .border({ width: 1 }) 
        .minFontSize(14) 
        .maxFontSize(24) 
      Text(this.truncatedHint) 
 
    }.width('100%') 
  } 
}
分享
微博
QQ
微信
回复
2024-06-12 23:45:55
相关问题
Text设置maxLines时使用Infinity报错
583浏览 • 1回复 待解决
Text换行无法在后面添加图片
304浏览 • 1回复 待解决
有没有获取当前网速的api?
2918浏览 • 1回复 待解决
如何判断har是否混淆了?
340浏览 • 1回复 待解决
有没有api可以杀掉当前进程
373浏览 • 1回复 待解决
有没有给canvas设置ColorFilter的方法?
347浏览 • 1回复 待解决
求大佬告知如何判断当前版本
559浏览 • 1回复 待解决
如何判断当前线程是否是主线程
741浏览 • 1回复 待解决
Java Text控件,如何设置字间距?
5464浏览 • 1回复 待解决
如何判断当前是release包还是debug包
541浏览 • 1回复 待解决
判断当前设备是手机还是平板
4698浏览 • 1回复 待解决
如何判断当前使用的是哪个sim卡流量
349浏览 • 1回复 待解决