Ios 在UITextField或UITextView中检测@,并比较是否自动完成
我正在尝试制作一些与Twitter在撰写Tweet时的工作方式相同的东西 我的应用程序使用与@username相同的语法发送消息。在我的compose视图中,我有一个UITextView/UITextField,用户在其中键入消息,我想检测用户何时键入@,然后将@后面的字符串与我拥有的用户名数组进行比较,以便自动完成 我一直在学习本教程,该教程非常出色: 这两种方法是我应该执行检测的地方:Ios 在UITextField或UITextView中检测@,并比较是否自动完成,ios,autocomplete,uitextfield,Ios,Autocomplete,Uitextfield,我正在尝试制作一些与Twitter在撰写Tweet时的工作方式相同的东西 我的应用程序使用与@username相同的语法发送消息。在我的compose视图中,我有一个UITextView/UITextField,用户在其中键入消息,我想检测用户何时键入@,然后将@后面的字符串与我拥有的用户名数组进行比较,以便自动完成 我一直在学习本教程,该教程非常出色: 这两种方法是我应该执行检测的地方: - (BOOL)textField:(UITextField *)textField shou
- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string {
autocompleteTableView.hidden = NO;
NSString *substring = [NSString stringWithString:textField.text];
substring = [substring
stringByReplacingCharactersInRange:range withString:string];
[self searchAutocompleteEntriesWithSubstring:substring];
return YES;
}
- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring {
// Put anything that starts with this substring into the autocompleteUrls array
// The items in this array is what will show up in the table view
[autocompleteUrls removeAllObjects];
for(NSString *curString in pastUrls) {
NSRange substringRange = [curString rangeOfString:substring];
if (substringRange.location == 0) {
[autocompleteUrls addObject:curString];
}
}
[autocompleteTableView reloadData];
}
我假设应该在这里检测@,但我不确定如何做到这一点,然后只比较紧跟在符号后面的字符(并在出现空白时停止比较)
标准的iOS twitter应用程序就是我想要的一个最好的例子。任何帮助都会很好,谢谢 使用
NSScanner
。在searchAutocompleteEntriesWithSubstring
方法中,使用substring
创建一个扫描器,并在循环中运行,首先搜索@
,然后在找到后搜索空间。然后可以使用扫描的字符串自动完成
根据您在查找匹配项时对字符串所做的操作,指定搜索算法的工作方式。您可能希望在
子字符串中找到最后一个@
的范围,并将扫描仪位置设置为该范围(以避免处理任何以前的用户名)-但是,您没有关于刚刚更改的内容的信息,因此用户返回并插入用户名…[str substringfromfromindex:[str rangeOfString:@“@]”。位置+1]
成功了。