2017-04-02 68 views
0

在UITextView中獲取遊標CGPoint有很多答案。但我需要找到與self.view(或手機屏幕邊框)相關的光標位置。在Objective-C中有這樣做的方法嗎?與self.view相關的遊標位置

回答

1

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