在 UITextView 中获取光标 CGPoint 有很多答案。但我需要找到与 self.view (或手机屏幕边框)相关的光标位置。在 Objective-C 中有没有办法做到这一点?
Best Answer-推荐答案 strong>
UIView 有一个 convert(_:to 方法可以做到这一点。它将坐标从接收坐标空间转换到另一个 View 坐标空间。
这是一个例子:
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.
}
swift
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.
}
关于ios - 相对于 self.view 的光标位置,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/43166781/
|