問題
Text部分字體變色,在應(yīng)用中處理是很常見的操作整袁。 RichText富文本組件账忘,解析并顯示HTML格式文本志膀,通HTML實(shí)現(xiàn)熙宇,但是這個(gè)不太好用,在跟其他組件一起使用時(shí)自適應(yīng)寬高的時(shí)候很難處理溉浙,要么就給固定寬高還可以烫止。
解決方式
目前我的處理方式是:Text要顯示的string做切割,然后用ForEach在Text中加Span組件戳稽,在Span組件中對文字做相應(yīng)的特殊處理馆蠕,這樣可保證Text屬性的延續(xù),又可以處理各種特殊情況惊奇,就是拆分互躬、計(jì)算等比較麻煩。
示例颂郎,高亮顯示代碼如下
export class StringUtils {
public static readonly REGEX_B_S = "<B>"
public static readonly REGEX_B_E = "</B>"
/**
* 獲取高亮字符串列表
* @param str 原始字符串
*/
public static getHlList(str ?: string, regex ?: string): HlContent[] {
if (str == undefined) {
return []
}
let list: HlContent[] = []
if (regex == undefined || !str.includes(regex)) {
let content = new HlContent()
content.content = str
list.push(content)
return list
}
if (StringUtils.REGEX_B_S == regex) {
let splitStr: string[] = str.split(regex)
for (let i = 0; i < splitStr.length; i++) {
let temp = StringUtils.getHlList(splitStr[i], StringUtils.REGEX_B_E)
if (temp != null && temp.length > 0) {
list = list.concat(temp)
}
}
}
if (StringUtils.REGEX_B_E == regex) {
let content1 = new HlContent()
content1.isHl = true
content1.content = str.substring(0, str.indexOf(regex))
list.push(content1);
let startIndex = str.indexOf(regex) + StringUtils.REGEX_B_E.length
let endIndex = str.length
if (startIndex < endIndex) {
let content2 = new HlContent()
content2.content = str.substring(startIndex, endIndex)
list.push(content2);
}
}
return list
}
}
export class HlContent {
content: string = ""
isHl: boolean = false
}
import { HlContent, StringUtils } from './StringUtils';
@Entry
@Component
struct Index {
@State text : string = '測試一下<B>高亮</B>其他位置再來一個(gè)<B>高亮</B>'
build() {
Column(){
Text(){
ForEach(StringUtils.getHlList(this.text, StringUtils.REGEX_B_S), (item: HlContent) => {
if (item != null && item.content != null && item.content.length > 0) {
if (item.isHl) {
Span(item.content).fontColor("#ffff4500")
} else {
Span(item.content).fontColor("#ff000000")
}
}
})
}.fontSize(18).textOverflow({ overflow: TextOverflow.Ellipsis })
.maxLines(1).fontWeight(FontWeight.Bold).margin({top:8})
}
}
}
總結(jié)
示例中只是一種情況的處理吼渡,可自行根據(jù)需求特殊處理。