Set cursor position of the editor control exactly where user tapped in Xamarin.forms

198 Views Asked by At

I am working in Xamarin.forms project. I want to set the cursor position of the Editor control exactly where the user tapped. I want to achieve this specifically in IOS (better to have a solution in Android too). I have gone through a couple of articles where they suggested using a custom renderer but I don't know how. I have gone through the following articles

https://social.msdn.microsoft.com/Forums/en-US/5bf7c17c-51c2-4e9e-bc09-73e9a5512fc3/how-to-change-the-cursor-position-of-entry-or-editor-programmatically?forum=xamarinforms

Set CursorPosition in Editor Xamarin Forms

Based on the above link, I have made a custom renderer of the Editor control. The code inside OnElementPropertyChanged in custom render keeps my cursor on the starting position of the editor control but I don't want this. The cursor position should change where the user tapped. we need to update the code inside the renderer according to my use-case.

public class CustomEditor : Editor
    {
    }

public class CustomEditorRenderer : EditorRenderer
    {
        public CustomEditorRenderer() { }

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);
            if (Control != null)
            {
                // just change this statement to the one that works.
                Control.SelectedTextRange = Control.GetTextRange(fromPosition: Control.BeginningOfDocument, toPosition: Control.BeginningOfDocument);
            }
        }
    }

I have to use Editor control, not Entry control because I want to enter text in multiple lines. Editor control doesn't have a CursorPosition property like Entry control.

Can anyone suggest a better way through a custom renderer or via utilizing TextChanged, Focused event?

1

There are 1 best solutions below

0
Zack On

You can change your Renderer code to change the cursor position:

//Change the cursor position to the fifth character
var test = Control.GetPosition(Control.BeginningOfDocument, 5);

Control.SelectedTextRange = Control.GetTextRange(test, test);

If you want to change the cursor to the user's clicked position, you need to get the user's clicked position and convert it to the corresponding index value. For getting the user's click position, you can refer to the documentation:Walkthrough: Using Touch in Xamarin.iOS