OStack程序员社区-中国程序员成长平台

标题: ios - 相对于 self.view 的光标位置 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 00:31
标题: ios - 相对于 self.view 的光标位置

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



Best Answer-推荐答案


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/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4