如何在具有多行自动换行的UITextView中找到光标Y的位置?

问题描述 投票:0回答:2

我需要在多行的UiTextView中找到光标位置或焦点位置。

谢谢,阿吉特

swift xamarin.ios uitextview
2个回答
0
投票

您可以通过使用以下代码来获取光标的当前position和当前rect

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;
    }
}

参考:etting-and-setting-cursor-position-of-uitextfield-and-uitextview-in-swiftcursor-position-in-relation-to-self-view


0
投票

您可以通过不同的方式在UITextView中获取光标的CGPoint(X和Y位置)。但是,您是否需要找到光标相对于self.view(或电话屏幕边框)的位置?如果是这样,我为您翻译了this答案到C#:

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.
}
© www.soinside.com 2019 - 2024. All rights reserved.