0

I need to find the cursor position or the focus position in an UiTextView with multiple lines.

theduck
  • 2,589
  • 13
  • 17
  • 23
AjitK
  • 33
  • 8

2 Answers2

0

You can get the current position and current rect of cursor by using following codes:

public partial class ViewController : UIViewController
{
    public ViewController (IntPtr handle) : base (handle)
    {
    }

    public override void ViewDidLoad ()
    {
        base.ViewDidLoad ();
        // Perform any additional setup after loading the view, typically from a nib.

        UITextView textF = new UITextView();
        textF.Frame = new CoreGraphics.CGRect(30,20,200,50);
        textF.Text = "testtesttesttesttesttesttesttesttesttest";
        textF.Delegate = new myTextDelegate();
        View.Add(textF);

    }
}

public class myTextDelegate : UITextViewDelegate {

    public override bool ShouldChangeText(UITextView textView, NSRange range, string text)
    {

        //To get the current Position
        var startPoint = textView.BeginningOfDocument;
        var selectRange = textView.SelectedTextRange;

        var currentPoint = textView.GetOffsetFromPosition(startPoint, selectRange.Start);

        Console.WriteLine(currentPoint);

        //To get the current Rect
        CoreGraphics.CGRect caretRect = textView.GetCaretRectForPosition(selectRange.End);

        Console.WriteLine(caretRect);

        return true;
    }
}

Refer: etting-and-setting-cursor-position-of-uitextfield-and-uitextview-in-swift and cursor-position-in-relation-to-self-view

nevermore
  • 15,432
  • 1
  • 12
  • 30
0

You can get the cursor's CGPoint (X and Y position) within a UITextView in different ways. But do you need to find the position of cursor in relation to self.view (or phone screen borders)? If so, I translated this answer to C# for you:

var textView = new UITextView();
UITextRange selectedRange = textView.SelectedTextRange;
if (selectedRange != null)
{
    // `caretRect` is in the `textView` coordinate space.
    CoreGraphics.CGRect caretRect = textView.GetCaretRectForPosition(selectedRange.End);

    // Convert `caretRect` in the main window coordinate space.
    // Passing `nil` for the view converts to window base coordinates.
    // Passing any `UIView` object converts to that view coordinate space.
    CoreGraphics.CGRect windowRect = textView.ConvertRectFromCoordinateSpace(caretRect, null);
}
else
{
    // No selection and no caret in UITextView.
}
Saamer
  • 4,687
  • 1
  • 13
  • 55