1

I am making a custom keyboard extension for iOS 8 and am unsuccessful at trying to reflect the current word being typed on a UILabel sitting on top of the keyboard (think autocorrect). So far the code I wrote reflects the sentence before the cursor and not as it's being written, but as the cursor is moved from one position to another. What I am trying to achieve is exactly like the first autocorrect box in the native keyboard. Would anyone mind telling me what I am doing wrong?

Code:

override func textWillChange(textInput: UITextInput) {

    var tokens = (self.textDocumentProxy as! UITextDocumentProxy).documentContextBeforeInput .componentsSeparatedByString(" ") as NSArray
    var lastWord = tokens.lastObject as! String
    println(lastWord)
    bannerView?.btn1.setTitle(lastWord, forState: .Normal)
 }

I've tried setting a condition whereby if beforeCursor contained either a space/period/comma to set the button title as "" but that is not efficient in the long run as I need to obtain words in order to be able to make an autocorrect feature.

Edit:

I've figured out how to get the word before the cursor (updated the code above), but not how to update the label as each letter is being added. func textWillChange(textInput: UITextInput)isn't working out. It's not me it's her.

Thanks!

cyril
  • 3,020
  • 6
  • 36
  • 61

1 Answers1

0

You should use the textDocumentProxy property of your UIInputViewController:

let proxy = self.textDocumentProxy as! UITextDocumentProxy

To get the word being typed, I would suggest something like this:

var lastWordTyped: String? {
        if let documentContext = proxy.documentContextBeforeInput as NSString? {
            let length = documentContext.length
            if length > 0 && NSCharacterSet.letterCharacterSet().characterIsMember(documentContext.characterAtIndex(length - 1)) {
                let components = documentContext.componentsSeparatedByCharactersInSet(NSCharacterSet.alphanumericCharacterSet().invertedSet) as! [String]
                return components[components.endIndex - 1]
            }
        }
        return nil
    }
matthias
  • 947
  • 1
  • 9
  • 27
  • Why does this get rid of numbers as well? – cyril Jul 29 '15 at 14:40
  • 1
    See the NSCharacterSet I'm using: NSCharacterSet.letterCharacterSet(), refer https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSCharacterSet_Class/ for alternatives. – matthias Jul 29 '15 at 15:19