Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextField get currently edited word

I'm working on an autocompletion component and I have one problem that I would like to solve in some easy way.

I want to support edits to autocompleted text, for example:

 blablabl @usertag blablabl

If user goes back and edits @usertag string, I would like to start autocompletion when it's edited.

Question is, how to get currently edited word from textfield. I thought about taking cursor position, seperate nsstring to word by " " (space) and count letters from first word to cursor position.

Is there any easier way for doing that?

like image 734
Grzegorz Krukowski Avatar asked Mar 19 '14 13:03

Grzegorz Krukowski


2 Answers

Ok I found a way to do it quite easily. Maybe someone will find it useful:

UITextRange* selectedRange = [textField selectedTextRange];
NSInteger cursorOffset = [textField offsetFromPosition:0 toPosition:selectedRange.start];
NSString* text = textField.text;
NSString* substring = [text substringToIndex:cursorOffset];
NSString* editedWord = [[substring componentsSeparatedByString:@" "] lastObject];
like image 80
Grzegorz Krukowski Avatar answered Sep 28 '22 00:09

Grzegorz Krukowski


Swift 4 Solution

   func getCurrentEditingWord() ->String? {
        let selectedRange: UITextRange? = self.textView.selectedTextRange
        var cursorOffset: Int? = nil
        if let aStart = selectedRange?.start {
            cursorOffset = self.textView.offset(from: self.textView.beginningOfDocument, to: aStart)
        }
        let text = self.textView.text
        let substring = (text as NSString?)?.substring(to: cursorOffset!)
        let editedWord = substring?.components(separatedBy: " ").last
        return editedWord
    }
like image 27
Prashant Tukadiya Avatar answered Sep 28 '22 00:09

Prashant Tukadiya