ios - 如何修复 UITableView 中的重复搜索结果

标签 ios objective-c iphone uitableview

我有一个带有搜索栏功能的 UITableView。但是,当我搜索任何关键字时(请参阅附件中的屏幕截图),搜索结果将重复并返回超过 1 个结果。

我的预期结果应该是搜索结果会根据输入的关键字相应地反射(reflect)出来。

非常感谢您的帮助。请帮助,谢谢。 enter image description here enter image description here

 @interface Friend_ViewController () <p></p>

@end

@implementation Friend_ViewController{
    NSMutableArray *tableData;
    UITableView *tableView;
    BOOL isFiltered;
    NSMutableArray *stateNamesArray;
    NSArray *searchResult;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    isFiltered =false;

    UIImage* image3 = [UIImage imageNamed:@"Add_Friend"];

    CGRect frameimg = CGRectMake(0,0, image3.size.width -10, image3.size.height);

    UIButton *btn_add_friends = [[UIButton alloc] initWithFrame:frameimg];
    [btn_add_friends setBackgroundImage:image3 forState:UIControlStateNormal];
    [btn_add_friends addTarget:self action:@selector(addFriendButtonDidPressed:)
              forControlEvents:UIControlEventTouchUpInside];
    [btn_add_friends setShowsTouchWhenHighlighted:YES];

    UIBarButtonItem *btn_add_friends_item =[[UIBarButtonItem alloc] initWithCustomView:btn_add_friends];
    self.navigationItem.rightBarButtonItem =btn_add_friends_item;

    stateNamesArray = @[@"Alabama", @"Alaska", @"Arizona", @"Arkansas", @"California", @"Colorado", @"Connecticut", @"Delaware", @"Florida", @"Georgia", @"Hawaii", @"Idaho", @"Illinois", @"Indiana", @"Iowa", @"Kansas", @"Kentucky", @"Louisiana", @"Maine", @"Maryland", @"Massachusetts", @"Michigan",
                                        @"Minnesota", @"Mississippi", @"Missouri", @"Montana", @"Nebraska", @"Nevada", @"New Hampshire",
                                        @"New Jersey", @"New Mexico", @"New York", @"North Carolina", @"North Dakota", @"Ohio",
                                        @"Oklahoma", @"Oregon", @"Pennsylvania", @"Rhode Island", @"South Carolina", @"South Dakota",
                                        @"Tennessee", @"Texas", @"Utah", @"Vermont", @"Virginia", @"Washington", @"West Virginia",
                                        @"Wisconsin", @"Wyoming"];


    NSInteger indexLabelLettersCount = [[UILocalizedIndexedCollation currentCollation] sectionTitles].count;

    NSMutableArray *allSections = [[NSMutableArray alloc] initWithCapacity:indexLabelLettersCount];

    for (int i = 0; i < indexLabelLettersCount; i++) {
        [allSections addObject:[NSMutableArray array]];
    }

    for(NSString *theState in stateNamesArray){


        NSInteger sectionNumber = [[UILocalizedIndexedCollation currentCollation] sectionForObject:theState collationStringSelector:@selector(lowercaseString)];

        [allSections[sectionNumber] addObject:theState];
    }
    NSMutableArray *sortedArray = [[NSMutableArray alloc] init];
    self.activeSectionIndices = [NSMutableDictionary dictionary];
    self.activeSectionTitles = [NSMutableArray array];

    for (int i = 0; i < indexLabelLettersCount; i++) {

        NSArray *statesForSection = allSections[i];

        NSString *indexTitleForSection = [[UILocalizedIndexedCollation currentCollation] sectionTitles][i];

        if (statesForSection.count > 0) {

            [self.activeSectionTitles addObject:indexTitleForSection];

            NSArray *tmpSectionStates = allSections[i];

            tmpSectionStates = [tmpSectionStates sortedArrayUsingSelector:@selector(compare:)];

            [sortedArray addObject:tmpSectionStates];
        }

        NSNumber *index = [NSNumber numberWithInt:MAX(self.activeSectionTitles.count - 1, 0)];

        self.activeSectionIndices[indexTitleForSection] = index;

    }

    tableData = sortedArray;

    self.tableView.sectionHeaderHeight = 25;
    self.navigationController.navigationBar.translucent = NO;

    tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.navigationController.navigationBar.translucent = NO;

    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];

    self.tableView.tableHeaderView = self.searchController.searchBar;

    self.searchController.searchResultsUpdater = self;
    self.searchController.dimsBackgroundDuringPresentation = NO;
    self.searchController.hidesNavigationBarDuringPresentation = NO;
    self.searchController.searchBar.delegate = self;


    self.definesPresentationContext = YES;
    [self.searchController.searchBar sizeToFit];

    [self.view addSubview:self.searchBar];
    searchResult = [NSMutableArray arrayWithCapacity:[stateNamesArray count]];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(nonnull NSString *)searchText
{
    if(searchText.length == 0)
    {
        isFiltered = NO;
    }
    else
    {
        isFiltered = YES;
        NSPredicate *resultPredicate = [NSPredicate
                                        predicateWithFormat:@"SELF CONTAINS %@",
                                        searchText];    
        searchResult = [stateNamesArray filteredArrayUsingPredicate:resultPredicate];      
    }
    [self.tableView reloadData];
}

- (NSInteger)numberOfSectionsInTableView: (UITableView *) tableView{
    return tableData.count;
}

- (NSInteger)tableView: (UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(isFiltered){
        return searchResult.count;
    }
    else
    {
        NSArray *arr = tableData[section];
        return arr.count;
    }
}

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if(cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }

    if(isFiltered){
        cell.textLabel.text = [searchResult objectAtIndex:indexPath.row];
        cell.imageView.image = [UIImage imageNamed:@"Home"];
    }
    else{

        NSArray *arr = tableData[indexPath.section];//get the current section array
        cell.textLabel.text = arr[indexPath.row];//get the row for the current section
        cell.imageView.image = [UIImage imageNamed:@"Home"];
    }
    return cell;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if(isFiltered)
    {
        return nil;
    }
    return self.activeSectionTitles[section];
}

@end
 </pre></code>

最佳答案

您总是在 numberOfSectionsInTableView 中返回 tableData.count,因此每一行都会重复 tableData.count 次。

- (NSInteger)numberOfSectionsInTableView: (UITableView *) tableView{
   return isFiltered ? 1 : tableData.count;
}


- (NSInteger)tableView: (UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  NSArray sectionArray = (NSArray *)tableData[section];
  return isFiltered ? 1 : sectionArray.count;
}

你总是在 numberOfSectionsInTableView 中返回 tableData.count 所以

关于ios - 如何修复 UITableView 中的重复搜索结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48071555/

相关文章:

ios - 使所有内容变暗,但选定的行 ios

ios - 自定义声音远程推送通知 iOS 不工作

ios - Swift - UIBarButtonItem.customView - 重置为原始状态

objective-c - 从 Apple TV TVML TVJS JavaScript 应用调用 Swift 代码

objective-c - xcode xib 文件中文件所有者的需求是什么?我可以在没有文件所有者的情况下做同样的事情吗?

iphone - 在 iOS 中选择 UILabel 时推送到另一个 View Controller

iphone - 为什么在加载 TableViewcontroller 时出现此错误

ios - cloudKit: CKSubscription 错误 "This request requires an authenticated account""

objective-c - 窗口 :willPositionSheet:usingRect doesn't get called

iphone - 节目收到信号SIGABRT