2012-07-05 1 views
3

나는 자동 완성을 위해 UITableView에 연결된 UITextView을 가지고있다.UITextView 자동 완성 텍스트 주문하지 않음

문제는 테이블 디스플레이가 제대로 포맷되지이다, 나는이 문제를 다음과 같습니다

  1. 을 세부 전 (순서대로되지 않습니다 : 내가 누르면 단어를 표시하지 않는 그것은 시작 첫째, 좋아하는대로 표시됩니다.)

  2. 나는 내 txt 파일에 3 가지 종류의 단어가 있습니다 (예 : Apple, A pple, A.pple). 내 테이블에 단지 pple과 A.pple이 표시되지만 애플이 아닌 경우 'Ap'라는 문자로 검색을 시작하면 'P'라고 쓸 때까지 pple이 표시됩니다.

무엇을해야할지 알려줄 수 있습니까?

참조를 위해 내 코드를 찾아주세요 :

모든 코드 내가 그 잘못 가고 있었다 찾을 수 없기 때문에, 내가 뭐하는 거지을 게시

죄송합니다!

- (void) finishedSearching { 
    [usernameField resignFirstResponder]; 
    autoCompleteTableView.hidden = YES; 
} 

- (void)viewDidLoad 
{ 
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"employee.txt" ofType:nil]; 
    NSData* data = [NSData dataWithContentsOfFile:filePath]; 
    //Convert the bytes from the file into a string 
    NSString* string = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding]; 

    //Split the string around newline characters to create an array 
    NSString* delimiter = @"\n"; 
    NSArray *item = [string componentsSeparatedByString:delimiter]; 
    elementArray = [[NSMutableArray alloc] initWithArray:item]; 
    usernameField = [[UITextField alloc] initWithFrame:CGRectMake(204, 405, 264, 31)]; 
    usernameField.borderStyle = 3; // rounded, recessed rectangle 
    usernameField.autocorrectionType = UITextAutocorrectionTypeNo; 
    usernameField.autocapitalizationType = UITextAutocapitalizationTypeNone; 
    usernameField.textAlignment = UITextAlignmentLeft; 
    usernameField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; 
    usernameField.returnKeyType = UIReturnKeyDone; 
    usernameField.font = [UIFont fontWithName:@"Trebuchet MS" size:20]; 
    usernameField.textColor = [UIColor blackColor]; 
    [email protected]"Login id"; 
    [usernameField setDelegate:self]; 
    [self.view addSubview:usernameField]; 

    autoCompleteArray = [[NSMutableArray alloc] init]; 
    autoCompleteTableView = [[UITableView alloc] initWithFrame:CGRectMake(204, 450, 264, tableHeight) style:UITableViewStylePlain]; 
    autoCompleteTableView.delegate = self; 
    autoCompleteTableView.dataSource = self; 
    autoCompleteTableView.scrollEnabled = YES; 
    autoCompleteTableView.hidden = YES; 
    autoCompleteTableView.rowHeight = tableHeight; 
    [self.view addSubview:autoCompleteTableView]; 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 
} 
- (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]; 

    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]; 
} 
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 
    [self.view endEditing:YES]; 
    [super touchesBegan:touches withEvent:event]; 
    [self finishedSearching]; 
} 

#pragma mark UITextFieldDelegate methods 

// Close keyboard when Enter or Done is pressed 
- (BOOL)textFieldShouldReturn:(UITextField *)textField {  
    BOOL isDone = YES; 

    if (isDone) { 
     [self finishedSearching]; 
     return YES; 
    } else { 
     return NO; 
    } 
} 

// String in Search textfield 
- (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; 
} 

#pragma mark UITableViewDelegate methods 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger) section { 

    //Resize auto complete table based on how many elements will be displayed in the table 
    if (autoCompleteArray.count >=3) { 
     autoCompleteTableView.frame = CGRectMake(204, 450, 264, tableHeight*3); 
     return autoCompleteArray.count; 
    } 

    else if (autoCompleteArray.count == 2) { 
     autoCompleteTableView.frame = CGRectMake(204, 450, 264, tableHeight*2); 
     return autoCompleteArray.count; 
    } 

    else { 
     autoCompleteTableView.frame = CGRectMake(204, 450, 264, tableHeight); 
     return autoCompleteArray.count; 
    } 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    UITableViewCell *cell = nil; 
    static NSString *AutoCompleteRowIdentifier = @"AutoCompleteRowIdentifier"; 
    cell = [tableView dequeueReusableCellWithIdentifier:AutoCompleteRowIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:AutoCompleteRowIdentifier] ; 
    } 

    cell.textLabel.text = [autoCompleteArray objectAtIndex:indexPath.row]; 
    return cell; 
} 


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath]; 
    usernameField.text = selectedCell.textLabel.text; 
    usernameField.text=[usernameField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; 

    NSLog(@"%@",usernameField.text); 
    [self finishedSearching]; 
} 



- (void)viewDidUnload 
{ 

    [super viewDidUnload]; 
    // Release any retained subviews of the main view. 
} 

감사합니다.

답변

2

이 코드를 따르십시오. U가 올바르게 완료되었지만 요소를 검색하는 것이 문제입니다. U가 코드를 작성했습니다. 혼자서 검사하는 길이라면. null가 아닌 경우는 데이터를 표시합니다. 하지만 첫 번째 문자를 요소 배열과 비교해야합니다. 그래서 잘 작동합니다.

- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring { 
    [autocompleteArray removeAllObjects]; 

    for(NSString *curString in elementArray) { 
     NSRange substringRange = [curString rangeOfString:substring]; 
     if (substringRange.location == 0) {    
      [autocompleteArray addObject:curString];   
     }   

     [autocompleteTableView reloadData]; 
    } 
} 
관련 문제