光标颜色
首先,我们可以通过 TextInput 组件的 caretColor 属性来改变输入法光标的颜色。
caretColor(value: ResourceColor): TextInputAttribute;
示例:
TextInput({ placeholder: "请输入内容" })
.width(300)
.height(50)
.caretColor(Color.Red)
运行结果:
从运行结果来看,光标的颜色变成了红色。
控制光标
除了可以设置光标的颜色,我们还可以控制光标的位置。
控制光标的位置需要用到 TextInput 组件的控制器。
也就是在构建 TextInput 组件的时候,可以传一个 TextInputController 对象。
declare class TextInputController {
constructor();
/**
* 改变光标位置
*/
caretPosition(value: number): void;
}
它里面有一个 caretPosition 函数,该函数的作用是改变光标位置。
接下来,我们来试试。
首先,我们需要在页面中定义一个 TextInputController 属性。
@Entry
@Component
export struct Index {
/**
* TextInput 组件控制器
*/
controller: TextInputController = new TextInputController()
build() {
}
}
然后,在 TextInput 组件中使用它。
@Entry
@Component
export struct Index {
/**
* TextInput 组件控制器
*/
controller: TextInputController = new TextInputController()
build() {
Column() {
TextInput({ placeholder: "请输入内容", controller: this.controller })
.width(300)
.height(50)
}
.width('100%')
}
}
最后,我们监听用户输入的内容,当内容长度超过 5 时,让输入法光标回到起始位置。
@Entry
@Component
export struct Index {
/**
* TextInput 组件控制器
*/
controller: TextInputController = new TextInputController()
build() {
Column() {
TextInput({ placeholder: "请输入内容", controller: this.controller })
.width(300)
.height(50)
.onChange(value => {
if (value.length > 5) {
this.controller.caretPosition(0);
}
})
}
.width('100%')
}
}
运行结果:
当我输入到“6”的时候,光标就移到起始位置了。
至此,输入框里关于光标的设置及控制我们就已经学会了。