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