创建 lastWordBeforeInput 方法...
-(NSString *) lastWordBeforeInput{
NSArray *arrayOfSplitsString = [self.textDocumentProxy.documentContextBeforeInput componentsSeparatedByString:@" "];
int countIndex = arrayOfSplitsString.count - 1;
NSCharacterSet *ChSet = [NSCharacterSet alphanumericCharacterSet];
NSCharacterSet *invertedChSet = [ChSet invertedSet];
while (countIndex > 0) {
NSString *lastWordOfSentance = [arrayOfSplitsString objectAtIndex:countIndex--];
if ([[lastWordOfSentance stringByTrimmingCharactersInSet:invertedChSet] rangeOfCharacterFromSet:ChSet].location != NSNotFound) {
return [lastWordOfSentance stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
}
return @"";
}
然后根据要求使用 textWillChange/textDidChange 调用它。
- (void)textWillChange:(id<UITextInput>)textInput {
// The app is about to change the document's contents. Perform any preparation here.
NSLog(@"%@",[self lastWordBeforeInput]);
}
希望这会帮助你。