2017-04-02 3 views
0

Es gibt viele Antworten, um Cursor CGPoint in UITextView zu erhalten. Aber ich muss eine Position des Cursors in Bezug auf self.view (oder Handy-Bildschirm Grenzen) finden. Gibt es einen Weg dazu in Objective-C?Cursorposition in Bezug auf self.view

Antwort

1

UIView hat eine convert(_:to:) Methode, die genau das tut. Er konvertiert Koordinaten aus dem Empfängerkoordinatenraum in einen anderen Ansichtskoordinatenraum. Hier

ein Beispiel:

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