[英]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). 我正在为iOS 8创建自定义键盘扩展名,但无法尝试反映出坐在键盘顶部的UILabel上正在键入的当前单词(请考虑自动更正)。 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. 我尝试设置一个条件,如果beforeCursor包含一个空格/句点/逗号来将按钮标题设置为
""
但是从长远来看,这是无效的,因为我需要获取单词才能进行自动更正特征。
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. func textWillChange(textInput: UITextInput)
无法正常工作。 It's not me it's her. 不是我,是她。
Thanks! 谢谢!
You should use the textDocumentProxy
property of your UIInputViewController
: 您应该使用
textDocumentProxy
你的财产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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.