在项目中我们经常会遇到同一段文本特定文字样式特殊处理的情况,如这是一段特殊文字这句话中对‘特殊’两个进行加粗、字体大小、改变颜色等进行突出显示。这个时候就用到属性字符串StyledString/MutableStyledStringMutableStyledString继承自StyledString使用方式为通过TextController提供的setStyledString方法将属性字符串附加到文本组件并推荐在onPageShow或者文本组件的onAppear回调中触发绑定。需要注意的是在aboutToAppear中调用setStyledString方法时由于该方法运行阶段组件尚未完成创建并成功挂载节点树因此无法在页面初始化时显示属性字符串。1、基础使用案例import{LengthMetrics}fromkit.ArkUI;BuilderexportfunctionMutableStyledStringPageBuilder(){MutableStyledStringPage()}ComponentV2exportstructMutableStyledStringPage{pageInfos:NavPathStacknewNavPathStack();private content:string这是测试一和测试二。;controller:TextControllernewTextController();// 文本控制器textStyleAttrs:TextStylenewTextStyle({fontWeight:FontWeight.Bold,// 字体粗细fontSize:LengthMetrics.vp(16),// 字体大小fontStyle:FontStyle.Normal,// 字体样式fontColor:Color.Black// 字体颜色});textStyleAttrs2:TextStylenewTextStyle({fontWeight:FontWeight.Bold,fontSize:LengthMetrics.vp(16),fontStyle:FontStyle.Normal,fontColor:Color.Red});build(){NavDestination(){Column(){Text(undefined,{controller:this.controller});// 使用controller对文字进行设置}.width(100%)}.onReady((context:NavDestinationContext){this.pageInfoscontext.pathStack// 推荐在onReady中使用但是不能使用条件渲染this.initStyledString();})}initStyledString(){// 不需要对文本渲染后进行改变使用StyledString反着使用MutableStyledStringconstmutableStrnewMutableStyledString(this.content,[{start:2,// 开始位置length:3,// 改变文字长度styledKey:StyledStringKey.FONT,// 文本类型styledValue:this.textStyleAttrs// 使用样式1},{start:6,length:3,styledKey:StyledStringKey.FONT,styledValue:this.textStyleAttrs2// 使用样式2}]);this.controller.setStyledString(mutableStr);// 设置样式}}2、应用文本阴影案例textStyleAttrs3:TextShadowStylenewTextShadowStyle({radius:5,type:ShadowType.COLOR,color:Color.Red,offsetX:10,offsetY:10})3、设置事件案例// 事件设置gestureStyleAttr:GestureStylenewGestureStyle({onClick:(){this.backgroundColor1Color.Green;},onLongPress:(){this.backgroundColor1Color.Grey;}});// 样式设置constmutableStrnewMutableStyledString(this.content,[{start:0,// 事件起始位length:1,// 长度styledKey:StyledStringKey.GESTURE,styledValue:this.gestureStyleAttr}最后效果为点击第一个文字改变背景颜色为绿色长按第一个文字背景颜色改变为灰色。日常开发中最常用的就是以上三种。如何动态修改特效特效文字index变更直接给出简单实现代码// 文本样式接口interfaceRangerItem{start:number,// 开始位置length:number,// 特效文字长度styledKey:StyledStringKey,// 文本类型styledValue:StyledStringValue// 使用样式}// 文本样式textStyleAttrs:TextStylenewTextStyle({fontWeight:FontWeight.Bold,// 字体粗细fontSize:LengthMetrics.vp(16),// 字体大小fontStyle:FontStyle.Normal,// 字体样式fontColor:Color.Black// 字体颜色});// 处理设置样式逻辑conststyledList:ArrayRangerItem[];// 创建文本样式列表// 这里是遍历获取需要特殊处理文字的逻辑根据各自逻辑编写// 提取需要处理的文字位置styledList.push({start:0,length:5,styledKey:StyledStringKey.FONT,styledValue:this.textStyleAttrs});// 这里根据实际情况移除多余的内容// 设置文字样式constmutableStrnewMutableStyledString(文本);this.controller.setStyledString(mutableStr);