【关键字】
ArkTS / TextInput / 设置字符选中
【问题描述】
打开 dialog 的时候,出现一个 textInput 组件,它存在默认值,并且希望当首次弹窗出现的时候,textInput 的文本就被全部选中并且聚焦,聚焦实现了,但是选中状态没有找到方法实现。
【解决方案】
创建一个TextInputController 对象,在Button组件的事件中调用 TextInputController 的 setTextSelection方法。setTextSelection必须在TextInput组件获焦时设置才生效,可以在TextInput组件的onFocus回调中设置setTextSelection。
Demo示例:
@Entry
@Component
struct Index {
controller:TextInputController = new TextInputController();
build() {
Row() {
TextInput({
text: '111111',
placeholder: '222222',
controller: this.controller
})
.width(300)
.defaultFocus(true)
.onFocus(() => {
this.controller.setTextSelection(0, 6)
})
}
.width('100%')
.height('100%')
}
}