iOS中UITextfield的自动完成

iOS中UITextfield的自动完成,ios,iphone,autocomplete,textfield,Ios,Iphone,Autocomplete,Textfield,我正在开发新的iOS应用程序。在那个应用程序中,我有5个UITextFields,它们是 1.第一个利息,第二个利息,最多5个利息 我需要为这5个UITextFields添加自动完成。我在谷歌搜索了一天。我有一些论坛和教程。但我甚至还尝试过Github链接 根据我的要求,我有一个从服务器获取的数据数组。在这个数组中,我有一些数据,比如咖啡、蟋蟀等,它们是自动完成的数据。每当用户在UITextField中输入文本时,我需要显示该数组,如果它与我的数据数组相关,则需要显示该UITextField的下

我正在开发新的iOS应用程序。在那个应用程序中,我有5个UITextFields,它们是 1.第一个利息,第二个利息,最多5个利息

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

根据我的要求,我有一个从服务器获取的数据数组。在这个数组中,我有一些数据,比如咖啡、蟋蟀等,它们是自动完成的数据。每当用户在UITextField中输入文本时,我需要显示该数组,如果它与我的数据数组相关,则需要显示该UITextField的下面部分

为此,我使用了以下代码

**//搜索文本字段中的字符串

- (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];
      }
我在
ViewDidLoad
方法中将UITableView创建为
AutocompleteTableview

**问题是,若我将文本输入为“c”,那个么从我的数据数组中,无论文本包含什么,都会在tableview中显示为“c”字母。但是,如果我键入“coff”,则UITableView中不会显示任何数据。另外,如何验证哪个UITextField用户在
TableViewDidSelectRowatingIndexPath
delegate方法中单击。我尝试为那些UITextFields分配标记,但它只在UITextFields委托方法中工作,而不在其他地方工作。所以,每当我从UITableView中选择数据时,第一个UITextField只获取数据,而不是其他UITextField

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


谢谢****

您可以使用以下链接,这些链接描述了我们如何使用自动完成功能。我尝试了AutocompletionTableview(第二个链接),它工作得非常好

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

取两个全局数组

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];
现在在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; 
}
编写搜索文本的方法

-(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的退格。
试试这个。希望这能满足您的要求。

以下是swift 3内联自动完成文本字段示例

  • 图像看起来像贝娄

  • 创建项目并添加文本字段。连接到名为txtAutoComplete的viewcontroller

  • 视图控制器代码如下

     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
        }
      }
    
    导入UIKit
    类ViewController:UIViewController、UIExtFieldDelegate{
    @IBOutlet弱var txtAutoComplete:UITextField!
    var自动完成可能性=[“01921687433”、“01553377642”、“0155776622”]
    var autoCompleteCharacterCount=0
    var timer=timer()
    重写func viewDidLoad(){
    super.viewDidLoad()
    txtAutoComplete.delegate=self
    }
    func textField(textField:UITextField,shouldchangeCharactersinrange:NSRange,replacementString:string)->Bool{//1
    var subString=(textField.text!。大写为NSString)。replacingCharacters(在:范围内,带:字符串)
    子字符串=格式化子字符串(子字符串:子字符串)
    如果subString.characters.count==0{
    //3当用户清除文本字段时
    重置值()
    }否则{
    SearchAutoCompleteTentriesWithSubString(子字符串:子字符串)
    }
    返回真值
    }
    func formatSubstring(子字符串:String)->String{
    设formatted=String(subString.characters.dropLast(autoCompleteCharacterCount)).lowercased().capitalized//5
    返回格式
    }
    func resetValues(){
    autoCompleteCharacterCount=0
    txtAutoComplete.text=“”
    }
    func SearchAutoCompleteTentriesWithSubString(substring:String){
    让userQuery=substring
    let suggestions=getautocompletessuggestions(userText:substring)
    如果0.count>0{
    timer=.scheduledTimer(withTimeInterval:0.01,repeats:false,block:{(timer)in//2
    让autocompleteResult=self.formatAutocompleteResult(子字符串:子字符串,可能匹配:建议)
    self.putColourFormattedTextInTextField(autocompleteResult:autocompleteResult,userQuery:userQuery)
    self.moveCaretToEndOfUserQueryPosition(userQuery:userQuery)
    })
    }否则{
    timer=.scheduledTimer(withTimeInterval:0.01,repeats:false,block:{(timer)in//7
    self.txtAutoComplete.text=子字符串
    })
    autoCompleteCharacterCount=0
    }
    }
    func getAutocompleteSuggestions(userText:String)->[String]{
    变量可能匹配:[String]=[]
    对于自动完成可能性{//2中的项
    让myString:NSString!=项作为NSString
    let substringRange:NSRange!=myString.range(of:userText)
    if(substringRange.location==0)
    {
    可能匹配。追加(项)
    }
    }
    返回可能匹配项
    }
    func PutColor FormattedTextIntextField(自动完成结果:字符串,用户查询:字符串){
    让coloredString:NSMutableAttributeString=NSMutableAttributeString(字符串:userQuery+autocompleteResult)
    coloredString.addAttribute(NSForegroundColorAttributeName,值:UIColor.green,范围:NSRange(位置:userQuery.characters.count,长度:autocompleteResult.characters.count))
    self.txtAutoComplete.AttributeText=彩色字符串
    }
    func moveCaretToEndOfUserQueryPosition(用户查询:字符串){
    如果让newPosition=self.txtAutoComplete.position(from:self.txtAutoComplete.BeginingOfDocument,offset:userQuery.characters.count){
    self.txtAutoComplete.selectedTextRange=self.txtAutoComplete.textRange(从:newPosition到:newPosition)
    }
    让selectedRange:UITextRange?=txtAutoComplete.SelectedExtrange
    txtAutoComplete.offset(从:txtAutoComplete.BeginingofDocument到:(selectedRange?.start)!)
    }
    func formatAutocompleteResult(子字符串:String,可能匹配:[String])->String{
    var autoCompleteResult=possi