UITEXTVIEW:获取最近在uitextview中输入的单词

时间:2012-12-29 19:12:16

标签: objective-c ios uitextview uimenucontroller

我想从UITextView获取用户输入的最新单词。

用户可以在UITextView中的任何位置,中间或末尾或开头输入单词。当用户完成输入并按空格并使用“UIMenuController”中的“建议”进行任何更正时,我会认为这是一个词。

示例:用户在文本中间某处的UITextView中的“kimd”中输入,他获得了自动更正的弹出“善意”,他做了。在他这样做之后,我想捕获“善意”并在我的应用程序中使用它。

我在互联网上搜索了很多,但找到了解决方案,谈论用户最终输入文本的时间。我也尝试检测一个空格然后进行向后搜索,直到找到一些文本之后的另一个空格,这样我就可以将其限定为一个单词。但我认为可能有更好的方法来做到这一点。

我在某处读过iOS缓存我们在文本字段或文本视图中输入的最新文本。如果我可以弹出顶部,那就是我想要的。我只需要处理那个对象。

我真的很感激帮助。

注意:用户可以在UItextview中的任何位置输入文本。我需要最新输入的单词

感谢。

4 个答案:

答案 0 :(得分:3)

//This method looks for the recent string entered by user and then takes appropriate action.

     - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {

 //Look for Space or any specific string such as a space
if ([text isEqualToString:@" "]) {
NSMutableCharacterSet *workingSet = [[NSCharacterSet whitespaceAndNewlineCharacterSet]   mutableCopy];

  NSRange newRange = [self.myTextView.text rangeOfCharacterFromSet:workingSet
                                     options:NSBackwardsSearch
                                     range:NSMakeRange(0, (currentLocation - 1))];

 //The below code could be done in a better way...
 UITextPosition *beginning = myTextView.beginningOfDocument;
 UITextPosition *start = [myTextView positionFromPosition:beginning offset:currentLocation];
 UITextPosition *end = [myTextView positionFromPosition:beginning   offset:newRangeLocation+1];
 UITextRange *textRange = [myTextView textRangeFromPosition:end toPosition:start];

 NSString* str = [self.myTextView textInRange:textRange]; 
}
}

答案 1 :(得分:2)

这是我建议做的,看起来有点hacky但是它可以正常工作:

首先在.h中符合UITextViewDelegate并将文字视图的delegate设置为self,如下所示:

myTextView.delegate = self;

并使用此代码:

- (void)textViewDidChange:(UITextView *)textView { // Delegate method called when any text is modified

if ([textView.text substringFromIndex: [textView.text length] - 1]) { // Gets last character of the text view's text

    NSArray *allWords = [[textView text] componentsSeparatedByString: @" "]; // Gets the text view's text and fills an array with all strings seperated by a space in text view's text, basically all the words

    NSString *mostRecentWord = [allWords lastObject]; // The most recent word!
}

}

答案 2 :(得分:1)

我使用此代码来获取@ -sign背后的单词:

- (void)textViewDidChange:(UITextView *)textView {
    NSRange rangeOfLastInsertedCharacter = textView.selectedRange;
    rangeOfLastInsertedCharacter.location = MAX(rangeOfLastInsertedCharacter.location - 1,0);
    rangeOfLastInsertedCharacter.length = 1;
    NSString *lastInsertedSubstring;
    NSString *mentionSubString;
    if (![textView.text isEqualToString:@""]) {
        lastInsertedSubstring = [textView.text substringWithRange:rangeOfLastInsertedCharacter];
        if (self.startOfMention > 0 || self.startOfHashtag > 0) {
            if ([lastInsertedSubstring isEqualToString:@" "] || (self.startOfMention > textView.selectedRange.location || self.startOfHashtag > textView.selectedRange.location)) {
                self.startOfMention = 0;
                self.lenthOfMentionSubstring = 0;
            }
        }
        if (self.startOfMention > 0) {
            self.lenthOfMentionSubstring = textView.selectedRange.location - self.startOfMention;
            NSRange rangeOfMentionSubstring = {self.startOfMention, textView.selectedRange.location - self.startOfMention};
            mentionSubString = [textView.text substringWithRange:rangeOfMentionSubstring];
            dhDebug(@"mentionSubString: %@", mentionSubString);

            UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil);

        }
    }
}

答案 3 :(得分:1)

extension UITextView { func editedWord() -> String { let cursorPosition = selectedRange.location let separationCharacters = NSCharacterSet(charactersInString: " ") let beginRange = Range(start: text.startIndex.advancedBy(0), end: text.startIndex.advancedBy(cursorPosition)) let endRange = Range(start: text.startIndex.advancedBy(cursorPosition), end: text.startIndex.advancedBy(text.characters.count)) let beginPhrase = text.substringWithRange(beginRange) let endPhrase = text.substringWithRange(endRange) let beginWords = beginPhrase.componentsSeparatedByCharactersInSet(separationCharacters) let endWords = endPhrase.componentsSeparatedByCharactersInSet(separationCharacters) return beginWords.last! + endWords.first! } } 的简单扩展名:

 library(tm)
 library(stringi)
 library(proxy)

 wiki <- "https://en.wikipedia.org/wiki/"

 titles <- c("Integral", "Riemann_integral", "Riemann-Stieltjes_integral",  "Derivative",
  "Limit_of_a_sequence", "Edvard_Munch", "Vincent_van_Gogh", "Jan_Matejko",
  "Lev_Tolstoj", "Franz_Kafka", "J._R._R._Tolkien")

 articles <- character(length(titles))

 for (i in 1:length(titles)) {
   articles[i] <- stri_flatten(readLines(stri_paste(wiki, titles[i])), col =     " ")
  }

 docs <- Corpus(VectorSource(articles))

 docs[[1]]
 docs2 <- tm_map(docs, function(x) stri_replace_all_regex(x, "<.+?>", " "))
 docs3 <- tm_map(docs2, function(x) stri_replace_all_fixed(x, "\t", " "))
 docs4 <- tm_map(docs3, PlainTextDocument)
 docs5 <- tm_map(docs4, stripWhitespace)
 docs6 <- tm_map(docs5, removeWords, stopwords("english"))
 docs7 <- tm_map(docs6, removePunctuation)
 docs8 <- tm_map(docs7, content_transformer(tolower))
 docs8[[1]]

 docsTDM <- DocumentTermMatrix(docs8)
 docsTDM2 <- as.matrix(docsTDM)
 docsdissim <- dist(docsTDM2, method = "cosine")

 docsdissim2 <- as.matrix(docsdissim)
 rownames(docsdissim2) <- titles
 colnames(docsdissim2) <- titles
 docsdissim2
 h <- hclust(docsdissim, method = "ward")
 plot(h, labels = titles, sub = "")