HarmonyOS鸿蒙Next中RichEditor通过addTextSpan方法追加字符,只能追加在末尾,如何追加在当前光标位置之前?
HarmonyOS鸿蒙Next中RichEditor通过addTextSpan方法追加字符,只能追加在末尾,如何追加在当前光标位置之前? demo如下:
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
controller: RichEditorController = new RichEditorController()
build() {
Column(){
RichEditor({ controller: this.controller })
.placeholder("文字...", {
font: {
size: 14,
weight: FontWeight.Normal,
family: "HarmonyOS Sans",
style: FontStyle.Normal
}
}
)
.width('100%')
.height(180)
.id('richEditor')
Button('添加@')
.onClick(() => {
this.controller.addTextSpan("@")
})
}
}
}

更多关于HarmonyOS鸿蒙Next中RichEditor通过addTextSpan方法追加字符,只能追加在末尾,如何追加在当前光标位置之前?的实战教程也可以访问 https://www.itying.com/category-93-b0.html
let caretOffset = editController.getCaretOffset();
editController.addImageSpan($r("app.media.sssss"), {//或者 textSpan
offset: caretOffset,
})
先获取光标位置。
更多关于HarmonyOS鸿蒙Next中RichEditor通过addTextSpan方法追加字符,只能追加在末尾,如何追加在当前光标位置之前?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
牛逼,大佬,解决了,感谢感谢。社区还是大佬多,
666,果然社区都是高手
666, 学习了
在HarmonyOS鸿蒙Next中,RichEditor的addTextSpan方法默认在末尾追加。要实现在当前光标位置前插入,需先获取光标位置。使用getSelection()方法获取Selection对象,从中取得光标偏移量(start)。然后通过getText()获取当前文本,将新内容插入到该位置,最后使用setText()更新。
在HarmonyOS Next的RichEditor中,addTextSpan方法默认在末尾追加内容。要在光标位置前插入,需要先获取光标位置,然后使用insertTextSpan方法。
具体步骤如下:
-
获取当前光标位置:通过
RichEditorController的getSelection方法获取当前选区的起始位置(selectionStart)。 -
在光标处插入:使用
insertTextSpan方法,将文本插入到获取到的光标位置。
修改后的代码示例:
Button('添加@')
.onClick(() => {
// 获取当前选区
const selection = this.controller.getSelection();
// 在光标起始位置插入"@"
this.controller.insertTextSpan(selection.selectionStart, "@");
})
关键点说明:
getSelection()返回当前选区信息,包括selectionStart(起始位置)和selectionEnd(结束位置)。insertTextSpan(offset: number, value: string)方法在指定的偏移量(offset)处插入文本。- 如果用户没有选中文本,
selectionStart和selectionEnd相同,即光标插入点。 - 此方法会直接修改编辑器内容,并自动更新光标位置。
这样即可实现在当前光标位置前插入指定文本,而不是始终追加到末尾。

