将光标移动到 TextField 的末尾 - Nativescript

Move cursor to the end of TextField - Nativescript

我希望文本字段在用户单击后自动指向文本末尾。这在使用 setSelection 之前是有效的,但由于某种原因它停止了工作。现在光标指向用户点击的地方。

HMTL:

<TextField text="the cursor should point at the end when clicked" (focus)="onFocus($event.object)"> </TextField>

TS:

public onFocus(textfield): void {
   textfield.android.setSelection(textfield.text.length)
}

如果我将它包装在超时内,它可以工作,但它会在光标移动之前闪烁,我对此不是很满意。我也做了一个playground example

在此先感谢您的帮助!

它似乎按预期工作。请记住,在 Android 焦点是光标放在 TextField 上时。如果您按下后退按钮隐藏键盘并单击 TextField 上的任意位置再次显示键盘,则不会再次触发焦点事件。

当我点击 TextField 时它会将光标指向 TextField 的末尾,如果我再次点击同一个 TextField 则不会。但是,如果我点击第二个 TextField,那么它应该会按预期工作,因为焦点现在从第一个 TextField 转移到第二个。

如果您仍有问题,请分享您的设备 OS 版本,并可能提供显示该问题的 GIF。

好的,我找到了解决方案。这有点像 hack,但它对我有用。与 setTimeout 的主要区别在于它不会在移动光标之前 'flash'。

好的,所以我的解决方案:我在文本字段内使用条件 css class,具体取决于文本字段是否获得焦点。一旦文本字段准备就绪,这会导致生命周期挂钩再次 运行(至少我认为这是正在发生的事情)。

这是我的代码: HTML:

<TextField [class.default-padding]="isFocused" text="the cursor should point at the end when clicked" (focus)="onFocus($event.object)" (blur)="onBlur()"> </TextField>

CSS:

.default-padding {
/* This is just a dummy value. You can use any other padding or margin or
 anything that will cause the hooks to re-render*/
padding-right: 0;

}

TS:

private isFocused = false

public onFocus(textfield): void {
    this.isFocused = true
    textfield.android.setSelection(textfield.text.length)
}

public onBlur(): void {
    this.isFocused = false
}

这是我的 updated playground example