maui

Setting cursor position for entry does not work on iOS


One of our entries are quite small, and hence when touched it places the cursor in front of the populated text. Text field

We want the cursor to be located at the end of the entry, so that it enables deletion and editing right away. I've added the following code in the focus handler to acheive this:

protected void Entry_Focused(object sender, FocusEventArgs e)
{
   System.Threading.Tasks.Task.Factory.StartNew(() =>
   {
      Thread.Sleep(100);
      entry.CursorPosition = entry.Text?.Length ?? 0;
   });
}

This works for Android, but on iOS. Is it possible to acheive this on iOS using Maui?


Solution

  • The reason it is probably not working is that you are not doing it on the correct thread or using the dispatcher to let it manage the thread try something like this:

    private async void Entry_Focused(object sender, FocusEventArgs e)
    {
         await Dispatcher.DispatchAsync(() =>
         {
             entry.CursorPosition = 0;
             //If you are trying to select the whole text otherwise ignore next line
             entry.SelectionLength = this.Text.Length; 
         });
    }
    

    Also why did you use Thread.Sleep why do that to your thread for no reason and why is your Focused event protected?