iOS中的UITextfield自动完成
我正在开发新的iOS应用程序。 在那个应用程序中,我有5个UITextFields,这些是1.第一兴趣,第二兴趣高达5兴趣。
我需要为这5个UITextField添加自动完成function。 我search了一天谷歌。 我有一些论坛和教程。 但我甚至用Github链接也尝试过。
根据我的要求,我有一个从我的服务器获得的数据。 在这个数组中,我有像咖啡,板球等数据。这是自动完成数据。 每当用户在UITextField中input文本时,我需要显示该数组,如果它与我的数据数组相关,则需要在该UITextFields的下方显示。
为此,我使用下面的代码。
** //search文本字段中的string
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSString *substring = [NSString stringWithString:textField.text]; substring = [substring stringByReplacingCharactersInRange:range withString:string]; [self searchAutocompleteEntriesWithSubstring:substring]; return YES; }
**
//从search文本字段获取string,并将其与自动完成数组进行比较
- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring { // Put anything that starts with this substring into the autoCompleteArray // The items in this array is what will show up in the table view [autoCompleteArray removeAllObjects]; NSLog(@"autoCompleteArray %@",autoCompleteArray); for(NSString *curString in elementArray) { NSRange substringRangeLowerCase = [curString rangeOfString:[substring lowercaseString]]; NSRange substringRangeUpperCase = [curString rangeOfString:[substring uppercaseString]]; if (substringRangeLowerCase.length != 0 || substringRangeUpperCase.length != 0) { [autoCompleteArray addObject:curString]; } } autoCompleteTableView.hidden = NO; [autoCompleteTableView reloadData]; }
我在ViewDidLoad
方法中创build了UITableView作为AutocompleteTableview
。
**问题是,如果我input文本为假设“C”,从我的数据显示任何文本在tableview中包含“C”字母的数组。 但是,如果我键入“coff”没有数据显示在该UITableView。 另外如何validation哪个UITextField用户在tableviewdidselectrowatindexpath
委托方法单击。 我试着为这些UITextFields分配标签,但是它只在UITextFields委托方法中工作,而不是在其他地方。 所以,每当我从UITableView中select数据,第一个UITextField只取数据而不是其他的UITextField。
请给出宝贵的build议,这是在iOS中为多个UITextfields显示UITextfields
自动完成的最好方法,以及如何处理显示数据的UITableView。 如果我的内容有任何错误,请原谅我,请提供宝贵的build议来解决这个问题。
谢谢****
以两个全局数组
NSMutableArray *muary_Interest_Main; NSMutableArray *muary_Interest_Sub;
IN viewDidLoad方法
muary_Interest_Main = [[NSMutableArray alloc]initWithObjects:@"Cricket",@"Dancing",@"Painting",@"Swiming",@"guitar",@"movie",@"boxing",@"drum",@"hockey",@"chessing",@"gamming", @"hunting",@"killing",@"shoping",@"jamm"@"zooming", nil]; muary_Interest_Sub = [[NSMutableArray alloc]init]; tbl_Search = [[UITableView alloc] initWithFrame: CGRectMake(4, 200, 320, 120) style:UITableViewStylePlain]; tbl_Search.delegate = self; tbl_Search.dataSource = self; tbl_Search.scrollEnabled = YES; [self.tbl_Search registerClass:[UITableViewCell class] forCellReuseIdentifier:@"CellIdentifier"]; [self.view addSubview:self.tbl_Search]; [tbl_Search setHidden:TRUE];
现在在textfield委托中写下如下的代码。
- (void)textFieldDidBeginEditing:(UITextField *)textField { NSLog(@"%d",textField.tag); int_TextFieldTag = textField.tag; [self searchText:textField replacementString:@"Begin"]; } - (BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; tbl_Search.hidden = TRUE; return YES; } - (void)textFieldDidEndEditing:(UITextField *)textField { tbl_Search.hidden = TRUE; } - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { [self searchText:textField replacementString:string]; return YES; }
写一个search文本的方法
-(void) searchText:(UITextField *)textField replacementString:(NSString *)string { if(int_TextFieldTag == 1) { tbl_Search.frame = CGRectMake(4, 200, 320, 120); } else if(int_TextFieldTag == 2) { tbl_Search.frame = CGRectMake(4, 248, 320, 120); } else if(int_TextFieldTag == 3) { tbl_Search.frame = CGRectMake(4, 268, 320, 120); } else if(int_TextFieldTag == 4) { tbl_Search.frame = CGRectMake(4, 268, 320, 120); } else { tbl_Search.frame = CGRectMake(4, 268, 320, 120); } NSString *str_Search_String=[NSString stringWithFormat:@"%@",textField.text]; if([string isEqualToString:@"Begin"]) str_Search_String=[NSString stringWithFormat:@"%@",textField.text]; else if([string isEqualToString:@""]) str_Search_String = [str_Search_String substringToIndex:[str_Search_String length] - 1]; else str_Search_String=[str_Search_String stringByAppendingString:string]; muary_Interest_Sub=[[NSMutableArray alloc] init]; if(str_Search_String.length>0) { NSInteger counter = 0; for(NSString *name in muary_Interest_Main) { NSRange r = [name rangeOfString:str_Search_String options:NSCaseInsensitiveSearch]; if(r.length>0) { [muary_Interest_Sub addObject:name]; } counter++; } if (muary_Interest_Sub.count > 0) { NSLog(@"%@",muary_Interest_Sub); tbl_Search.hidden = FALSE; [self.tbl_Search reloadData]; } else { tbl_Search.hidden = TRUE; } } else { [tbl_Search setHidden:TRUE]; } }
Tableview委托方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [muary_Interest_Sub count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"CellIdentifier"]; //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; ; } cell.textLabel.text = [muary_Interest_Sub objectAtIndex:indexPath.row]; return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [self.view endEditing:YES]; if(int_TextFieldTag == 1) { txt1.text=[muary_Interest_Sub objectAtIndex:indexPath.row]; } else if(int_TextFieldTag == 2) { txt2.text=[muary_Interest_Sub objectAtIndex:indexPath.row]; } else if(int_TextFieldTag == 3) { txt3.text=[muary_Interest_Sub objectAtIndex:indexPath.row]; } else if(int_TextFieldTag == 4) { txt4.text=[muary_Interest_Sub objectAtIndex:indexPath.row]; } else { txt5.text=[muary_Interest_Sub objectAtIndex:indexPath.row]; } }
这也适用于textfield的退格。 尝试这个。 希望这将适合您的要求。
- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring{ //Assume this array is the autocomplete array for which you get data from server NSMutableArray *autoCompleteArray = [[NSMutableArray alloc] initWithObjects:@"Coffee",@"Cricket",@"Volleyboll",nil]; text = [text stringByReplacingOccurrencesOfString:@" " withString:@""]; // This is to create predicate filter for getting matched text NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] %@",text]; // store matched data for autocompletion in results array and reload data in your tableview based on this array's data NSArray *resultArray = [[NSArray alloc] initWithArray:[autoCompleteArray filteredArrayUsingPredicate:predicate]]; }
您可以使用以下链接来描述我们如何使用自动完成function。 我尝试了AutocompletionTableview(第二个链接),它完美的工作。
这里是快速的3行内嵌自动完成文本框的例子
-
形象看起来像波纹pipe
-
创build一个项目并添加一个文本框。 连接到名为txtAutoComplete的视图控制器
-
查看控制器代码波纹pipe
import UIKit class ViewController: UIViewController ,UITextFieldDelegate{ @IBOutlet weak var txtAutoComplete: UITextField! var autoCompletionPossibilities = ["01921687433", "01553377642", "0155776622"] var autoCompleteCharacterCount = 0 var timer = Timer() override func viewDidLoad() { super.viewDidLoad() txtAutoComplete.delegate = self } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { //1 var subString = (textField.text!.capitalized as NSString).replacingCharacters(in: range, with: string) subString = formatSubstring(subString: subString) if subString.characters.count == 0 { // 3 when a user clears the textField resetValues() } else { searchAutocompleteEntriesWIthSubstring(substring: subString) } return true } func formatSubstring(subString: String) -> String { let formatted = String(subString.characters.dropLast(autoCompleteCharacterCount)).lowercased().capitalized //5 return formatted } func resetValues() { autoCompleteCharacterCount = 0 txtAutoComplete.text = "" } func searchAutocompleteEntriesWIthSubstring(substring: String) { let userQuery = substring let suggestions = getAutocompleteSuggestions(userText: substring) if suggestions.count > 0 { timer = .scheduledTimer(withTimeInterval: 0.01, repeats: false, block: { (timer) in //2 let autocompleteResult = self.formatAutocompleteResult(substring: substring, possibleMatches: suggestions) self.putColourFormattedTextInTextField(autocompleteResult: autocompleteResult, userQuery : userQuery) self.moveCaretToEndOfUserQueryPosition(userQuery: userQuery) }) } else { timer = .scheduledTimer(withTimeInterval: 0.01, repeats: false, block: { (timer) in //7 self.txtAutoComplete.text = substring }) autoCompleteCharacterCount = 0 } } func getAutocompleteSuggestions(userText: String) -> [String]{ var possibleMatches: [String] = [] for item in autoCompletionPossibilities { //2 let myString:NSString! = item as NSString let substringRange :NSRange! = myString.range(of: userText) if (substringRange.location == 0) { possibleMatches.append(item) } } return possibleMatches } func putColourFormattedTextInTextField(autocompleteResult: String, userQuery : String) { let colouredString: NSMutableAttributedString = NSMutableAttributedString(string: userQuery + autocompleteResult) colouredString.addAttribute(NSForegroundColorAttributeName, value: UIColor.green, range: NSRange(location: userQuery.characters.count,length:autocompleteResult.characters.count)) self.txtAutoComplete.attributedText = colouredString } func moveCaretToEndOfUserQueryPosition(userQuery : String) { if let newPosition = self.txtAutoComplete.position(from: self.txtAutoComplete.beginningOfDocument, offset: userQuery.characters.count) { self.txtAutoComplete.selectedTextRange = self.txtAutoComplete.textRange(from: newPosition, to: newPosition) } let selectedRange: UITextRange? = txtAutoComplete.selectedTextRange txtAutoComplete.offset(from: txtAutoComplete.beginningOfDocument, to: (selectedRange?.start)!) } func formatAutocompleteResult(substring: String, possibleMatches: [String]) -> String { var autoCompleteResult = possibleMatches[0] autoCompleteResult.removeSubrange(autoCompleteResult.startIndex..<autoCompleteResult.index(autoCompleteResult.startIndex, offsetBy: substring.characters.count)) autoCompleteCharacterCount = autoCompleteResult.characters.count return autoCompleteResult } }
-
源代码提供给GitHub.GitHub链接: https : //github.com/enamul95/AutoCompleteTextField