2014-09-30 44 views
1

我正在开发新的iOS应用程序。在那个应用程序中,我有5个UITextFields和那些是 1.第一兴趣,第二兴趣高达5兴趣。iOS中的UITextfield的自动完成

我需要为这5个UITextField添加自动完成功能。我在谷歌搜索了一天。我有一些论坛和教程。但我甚至尝试过使用Github链接。

根据我的要求,我有一个从我的服务器获取的数据数组。在这个数组中,我有数据,如咖啡,板球等。这是自动完成数据。每当用户在UITextField中输入文本时,如果与我的数据数组相关,需要在该UITextFields的下方显示该数组,则需要显示该数组。

为此我使用了以下代码。

** //在搜索文本框字符串

- (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; 
} 

**

//从搜索文本字段以字符串,并将其与自动完成阵列比较

- (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]; 
     } 

我创建的UITableView为AutocompleteTableview in ViewDidLoad方法。

**问题是,如果我输入文本为假设“c”,从我的数组数组中显示任何文本在tableview中包含“c”字母的数据。但是,如果我在那个UITableView中键入“coff”没有数据显示。还有如何验证哪个UITextField用户点击了tableviewdidselectrowatindexpath委托方法。我试着为这些UITextFields分配标签,但它只在UITextFields委托方法中工作,而不是在其他地方工作。所以,每当我从UITableView中选择数据,第一个UITextField只取数据而不是其他UITextField。

请给出宝贵的建议,这是在iOS中为多个UITextfields显示UITextfields的自动完成的最佳方式,以及如何处理显示数据的UITableView。如果我的内容中有任何错误可以原谅我,请提供宝贵的建议以解决此问题。

感谢****

+0

您是否尝试过任何回答四位,或只是张贴问题? – Maul 2014-09-30 07:19:54

+0

您输入**“coff”或“coff”? – abhishekkharwar 2014-09-30 07:54:03

+0

它的coff只,而我发布的问题,我让它大胆这就是为什么它显示出一些错误 – 2014-09-30 08:03:56

回答

2

举两个全局数组

NSMutableArray *muary_Interest_Main; 
NSMutableArray *muary_Interest_Sub; 

在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]; 

现在写在文本框代表一个下面的代码。

- (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; 
} 

写方法搜索文本

-(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]; 

    } 

} 

泰伯维委托方法

- (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]; 
} 

} 

这也适用于文本框的退格。 试试这个。希望这会适合您的要求。

+0

您的疑问是什么? – Maul 2014-09-30 07:20:53

+0

txt_Interest是您的texfield名称,如果用户开始在该字段中输入,那么然后该方法将调用 – Maul 2014-09-30 07:22:45

+0

如果您想要对所有textFiled进行相同的操作并使用相同的数组,则不需要检查条件只是调用方法 – Maul 2014-09-30 07:28:08

2
- (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]]; 
} 
+0

感谢您的快速解决方案,这是整体解决方案? – 2014-09-30 10:20:00

+0

这是用于自动完成搜索并将其显示在您的tableview中的逻辑。 – 2014-09-30 10:32:33

+0

这不是工作? – 2014-09-30 10:32:58

0

这里是SWIFT 3自动完成功能文本框例如

  1. 图片看起来像波纹管 enter image description here

  2. 创建一个项目&添加一个文本框。连接到视图控制器命名txtAutoComplete

  3. 查看控制器代码波纹管

    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 
        } 
        } 
    
  4. 的源代码提供给GitHub.GitHub链接:https://github.com/enamul95/AutoCompleteTextField