Another way I decided to do this is as follows.
In the function - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
I place a listener for the dialed #, which starts writing down the characters following the hash until the user types the space in which it is flushed.
if ([text isEqualToString:@"#"]) { recordingHashTag = YES; startParse = range.location; }else if ([text isEqualToString:@" "]) { currentHashTag = nil; recordingHashTag = NO; theTable.hidden = YES; } if (recordingHashTag == YES) { NSString *value; if (startParse > [textView.text length] - startParse) { value = [textView.text substringWithRange:NSMakeRange(startParse, [textView.text length] - startParse)]; [self filterHashTagTableWithHash:value]; } }
If BOOL recordingHashTag
set to YES
, I pass a substring
containing hashtag text to a function that looks for a pre-populated hashtag array. If there is a match, he adds this entry to the filtered hashtag array that he uses to populate the tableview
on the fly.
-(void)filterHashTagTableWithHash:(NSString *)hash{ [self.filterHashTagArray removeAllObjects]; for (NSString *hashTag in self.hashTagArray ){ NSRange result = [hashTag rangeOfString:hash options:NSCaseInsensitiveSearch]; if (result.location != NSNotFound) { [filterHashTagArray addObject:hashTag]; } } if (filterHashTagArray.count) { theTable.hidden = NO; }else{ theTable.hidden = YES; } [self.theTable reloadData]; }
The final step is to insert the hash tag when the user clicks on an entry in the table.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ UITableViewCell *cell = (UITableViewCell*)[self tableView:theTable cellForRowAtIndexPath:indexPath]; NSString *newString = [textViewComment.text stringByReplacingCharactersInRange:NSMakeRange(startParse, [textViewComment.text length] - startParse) withString:cell.textLabel.text]; textViewComment.text = newString; }
Just remember to clear your variables when the user pays attention to the middle hash tag.
Bueno source share