与self.view相关的游标位置

时间:2017-04-02 09:30:59

标签: ios objective-c position cursor

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

1 个答案:

答案 0 :(得分:2)

UIView有一个convert(_:to:)方法就是这么做的。它将坐标从接收器坐标空间转换为另一个视图坐标空间。

以下是一个例子:

<强>目标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.
}

<强>夫特

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