2013-03-19 1 views
0

У меня есть текстовое поле, из которого я хочу, чтобы пользователь вводил какие-либо данные, и он соответствует какой-либо ячейке в tableView, тогда он должен показывать. Я использовал текстовое поле для поиска данных из таблицы.Как искать данные из таблицыView в ipad и показывать эти данные в одной таблице.

Это как, я заселение данные в Tableview, как показано ниже:

 - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 
    { 

    NSLog(@"Number of Sections"); 
    if(section == 0) 
    return @"Sales"; 
    if(section == 1) 
    return @"Soft Skills"; 
    } 

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


     if (section==0) 
    { 
    appDelegate = (MultipleDetailViewsWithNavigatorAppDelegate *)[[UIApplication sharedApplication] delegate]; 

    int count=[resultArray count]; 

    NSLog(@"resultArry Row Counts is %d",count); 

    return [resultArray count]; 
    } 

     else{ 
    appDelegate = (MultipleDetailViewsWithNavigatorAppDelegate *)[[UIApplication sharedApplication] delegate]; 

    int count=[resultArrayOne count]; 

    NSLog(@"resultArry Row Counts is %d",count); 

    return [resultArrayOne count]; 
     } 
     } 


     - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  

     { 

    NSLog(@"Table Cell Data"); 
    static NSString *CellIdentifier = @"Cell"; 

     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

     if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 

     } 

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 


    if (indexPath.section==0) { 


    appDelegate = (MultipleDetailViewsWithNavigatorAppDelegate *)[[UIApplication sharedApplication] delegate]; 


    ObjectData *theCellData = [resultArray objectAtIndex:indexPath.row]; 
    NSString *cellValue =theCellData.sub_Category; 
    NSLog(@"Cell Values %@",cellValue); 
    cell.textLabel.text = cellValue; 

    return cell; 

     } 

     else { 

    appDelegate = (MultipleDetailViewsWithNavigatorAppDelegate *)[[UIApplication sharedApplication] delegate]; 
    ObjectData *theCellData = [resultArrayOne objectAtIndex:indexPath.row]; 
    NSString *cellValue =theCellData.sub_Category; 
    NSLog(@"Cell Values %@",cellValue); 
    cell.textLabel.text = cellValue; 
    return cell; 

    } 
      } 


     -(void)textFieldTextDidChange:(UITextField*)tf{ 



    NSString*test = searchTextField.text ; 

    } 
+0

См. Документы для 'UISearchDisplayController' и посмотрите пример приложения Apple Table TableSearch. – rmaddy

+0

используйте панель поиска вместо uitextfield – Kasaname

+0

, пожалуйста, Google это мой Frnd есть много аналогичных примеров. Предоставьте человеку-пользователю также пример кода яблока –

ответ

0

попробовать, как это может быть, это поможет вам,

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { 

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] %@", txtSearch.text]; 
    NSArray *ResultArray = [yourArray filteredArrayUsingPredicate:predicate]; 
    [table reloadData]; 
    return YES; 
} 

в коде выше замените Ваш массив.

Если вы хотите показать данные таблицы, которые имеют подстроку текстового поля, используйте ниже код.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@", txtSearch.text]; 
+0

Как вызвать этот метод –

+0

выше метод является методом делегата текстового поля, поэтому вы можете установить делегат в текстовое поле. – Balu

+0

это ошибка при завершении приложения из-за неперехваченного исключения «NSInvalidArgumentException», причина: «Невозможно выполнить операцию подстроки с чем-то, что не является строкой (lhs = rhs =) ' –

0

Поиск данных от UITableview, Вы можете использовать SearchBar. вы можете увидеть во многих проектах Denmo или в примере все могут использовать SearchBar в поиске данных в Tableview. ниже код SearchBar.

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{ 

    searchName = [[NSMutableArray alloc]init] ; 
    for(NSString *name in yourArraySeaching) 
    { 
     NSRange r = [name rangeOfString:searchText options:NSCaseInsensitiveSearch]; 

     if(r.location != NSNotFound) 
     { 
      [searchName addObject:name]; 
      tempSearch=1; 
     } 
    }  
} 
0

Прежде всего, вам нужен еще один временного массив для поиска цели таких же, как основных массив, один массива сохранения поиска идентификаторов буев.

логическое значение для поиска :: bool searching;

Code ::

-(void)textFieldTextDidChange:(UITextField*)tf { 

    int len = [[tf.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]; 

    if (len < [mainArray count]) { 

     [tempArray removeAllObjects]; 
     [tempArrayIds removeAllObjects]; 

     for(NSString *curString in tempArray) 
     { 
      NSString *substringRange = [curString substringWithRange:NSMakeRange(0, tf.length)]; 

      // Converting SearchChar and Firstchar of contestname into lower case 

      NSString *searchChar = [tf lowercaseString]; 
      NSString *FirstChar = [substringRange lowercaseString]; 

      //NSLog(@"values is %@",substringRange); 

      if ([FirstChar isEqualToString:searchChar]) { 

       if ([tf isEqualToString:@""]) { 

        searching = false; 
        [tf resignFirstResponder]; 
       } 
       else 
       { 
        searching = true; 
        [tempArray addObject:curString]; 

        indexVal = [tempArray indexOfObject:curString]; 

        NSString *s = [NSString stringWithFormat:@"%d", indexVal]; 
        [tempArrayIds addObject:s]; 
       } 
      } 
     } 
     [tblView reloadData]; 
    } 

Таблица Методы ::

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

    if (searching) 
     return [tempArray count]; 
    else 
     return [mainArray count]; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    if(searching) 
    { 
     int k = [[tempArrayIds objectAtIndex:indexPath.row] intValue]; 
     cell.title.text = [mainArray objectAtIndex:k]; 
    } 
    else 
    { 
     cell.title.text = [mainArray objectAtIndex:indexPath.row]; 
    } 
    return cell; 
} 

Будем надеяться, что это поможет.

Спасибо.

+0

, но у меня есть два раздела таблицы, и у меня есть два массива для двух разделов –

+0

, для которых вы можете заменить «mainArray» на любой массив, который вы хотите для поиска. –

0

Обычно я предпочитаю использовать свободно доступную среду Sensible TableView для этого. Структура будет извлекать данные и автоматически выполнять все функции поиска.

Смежные вопросы