与 self.view 相关的光标位置

eka*_*ing 2 position objective-c cursor ios

在 UITextView 中获取光标 CGPoint 有很多答案。但我需要找到光标相对于 self.view (或手机屏幕边框)的位置。Objective-C 有没有办法做到这一点?

dea*_*eef 5

UIView有一个convert(_:to:)方法可以做到这一点。它将坐标从接收器坐标空间转换到另一个视图坐标空间。

这是一个例子:

Objective-C

UITextView *textView = [[UITextView alloc] initWithFrame:CGRectZero];
UITextRange *selectedTextRange = textView.selectedTextRange;
if (selectedTextRange != nil)
{
    // `caretRect` is in the `textView` coordinate space.
    CGRect caretRect = [textView caretRectForPosition:selectedTextRange.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.
    CGRect windowRect = [textView convertRect:caretRect toView:nil];
}
else {
    // No selection and no caret in UITextView.
}
Run Code Online (Sandbox Code Playgroud)

迅速

let textView = UITextView()
if let selectedRange = textView.selectedTextRange
{
    // `caretRect` is in the `textView` coordinate space.
    let caretRect = textView.caretRect(for: 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.
    let windowRect = textView.convert(caretRect, to: nil)
}
else {
    // No selection and no caret in UITextView.
}
Run Code Online (Sandbox Code Playgroud)