我有一个 Spark TextArea:
<s:TextArea id="editor">
<s:textFlow>
<s:TextFlow id="_tf" >
<s:p>Lorem ipsum etc.</s:p>
<s:p>
<s:img source="http://example.com/example.jpg" />
</s:p>
<s:p>Aliquam tincidunt tempor etc.</s:p>
</s:TextFlow>
</s:textFlow>
</s:TextArea>
还有一个添加图像的按钮:
<s:Button id="imageBtn"
label="insert image"
width="89"
click="imageBtn_clickHandler(event);" />
以下脚本有效:
import flashx.textLayout.elements.*;
import mx.events.FlexEvent;
protected function imageBtn_clickHandler(evt:MouseEvent):void {
var img:InlineGraphicElement = new InlineGraphicElement();
img.source = "http://example.com/example.jpg";
var p:ParagraphElement = new ParagraphElement();
p.addChild(img);
_tf.addChild(p);
_tf.flowComposer.updateAllControllers();
editor.setFocus();
}
但仅附加到 TextFlow 的末尾。如何在 TextArea 的活动插入符号处插入 InlineGraphicElement?我的第一个想法是这样的:
import flashx.textLayout.elements.*;
import mx.events.FlexEvent;
protected function imageBtn_clickHandler(evt:MouseEvent):void {
var img:InlineGraphicElement = new InlineGraphicElement();
img.source = "http://example.com/example.jpg";
var p:ParagraphElement;
//pseudocode
p = _tf.getCaret.AncestorThatIsParagraphElement;
// end pseudocode
p.addChild(img);
_tf.flowComposer.updateAllControllers();
editor.setFocus();
}
但这仍然只会附加在当前段落的末尾,假设我什至可以找到当前段落作为 .addChild() 的对象。那么如何在 TextFlow 对象的子段落中的文本中间插入 InlineGraphicElement(甚至替换文本)。
感谢您的洞察力。
更新:越来越近。
我可以添加到段落的开头或结尾。
protected function imageBtn_clickHandler(evt:MouseEvent):void {
var img:InlineGraphicElement = new InlineGraphicElement();
img.source = "http://example.com/example.jpg";
var insertInto:ParagraphElement = new ParagraphElement();
insertInto = editor.textFlow.getChildAt(
editor.textFlow.findChildIndexAtPosition(
editor.selectionAnchorPosition
)).getParagraph();
insertInto.addChildAt(0, img); // inserts at beginning of paragraph
insertInto.addChildAt(1, img); // inserts at end of paragraph
_tf.flowComposer.updateAllControllers();
editor.setFocus();
}
但是插入中间仍然没有乐趣。此外,上面的代码不会替换突出显示的文本,但这不是这里真正关心的问题。
解决方案:
基于 Eugene 的链接,关键是 EditManager。
以下代码表示工作更新功能:
protected function imageBtn_clickHandler(evt:MouseEvent):void {
var em:EditManager = editor.textFlow.interactionManager as EditManager;
em.selectRange(editor.selectionAnchorPosition, editor.selectionActivePosition);
em.insertInlineGraphic("http://example.com/example.jpg","auto","auto");
_tf.flowComposer.updateAllControllers();
editor.setFocus();
}