光标位置与self.view的关系 [英] Cursor position in relation to self.view

查看:67
本文介绍了光标位置与self.view的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多答案可以在UITextView中获取光标CGPoint.但是我需要找到相对于self.view(或电话屏幕边框)的光标位置.在Objective-C中有办法吗?

There are many answers to get cursor CGPoint within UITextView. But I need to find a position of cursor in relation to self.view (or phone screen borders). Is there a way to do so in Objective-C?

推荐答案

UIView 具有完全实现此目的的 convert(_:to:)方法.它将坐标从接收者坐标空间转换为另一个视图坐标空间.

UIView has a convert(_:to:) method that does exactly that. It converts coordinates from the receiver coordinate space to another view coordinate space.

这里是一个例子:

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

快速

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

这篇关于光标位置与self.view的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆