简体   繁体   中英

How to get the current word being typed?

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!

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
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM