I need to find the cursor position or the focus position in an UiTextView with multiple lines.
Asked
Active
Viewed 801 times
0
-
try this solution https://stackoverflow.com/questions/43166781/cursor-position-in-relation-to-self-view – Alexandr Kolesnik Dec 05 '19 at 12:12
2 Answers
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
-
I tried the link but got only the X position not the Y. Is there anything extra I need to check? – AjitK Dec 09 '19 at 11:45
-
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
-
-
So the windowRect and caretRect don't provide you with the information you need? – Saamer Dec 09 '19 at 18:38