UISearchDisplayController在searchResultsTableView中不显示结果

set*_*fri 4 search objective-c uitableview uisearchdisplaycontroller ios

我已UISearchDisplayController正确连接到UITableViewIB 中的自定义标题.但是,当我搜索任何内容时,searchResultsTableView只显示"无结果",而我似乎无法找到代码不正确的位置.

searchResults 属性

- (NSMutableArray *)searchResults {
    if (!_searchResults) {
        _searchResults = [[NSMutableArray alloc] initWithCapacity:self.listingPreviews.count];
    }

    return _searchResults;
}
Run Code Online (Sandbox Code Playgroud)

表视图数据源方法

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    NSInteger numberOfRows = 0;

    if (tableView == self.tableView) {
        numberOfRows = self.listingPreviews.count;
    } else {
        numberOfRows = self.searchResults.count;
    }

    return numberOfRows;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Listing";
    ListingPreviewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (!cell) {
        cell = [[ListingPreviewTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    // Configure the cell.
    if (tableView == self.tableView) {
        cell.listingPreview = [self.listingPreviews objectAtIndex:indexPath.row];
    } else {
        NSLog([[self.searchResults objectAtIndex:indexPath.row] title]);
        cell.listingPreview = [self.searchResults objectAtIndex:indexPath.row];
    }

    return cell;
}
Run Code Online (Sandbox Code Playgroud)

搜索栏代表方法

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    NSInteger searchTextLength = searchText.length;

    for (ListingPreview *listingPreview in self.listingPreviews) {
        if ((listingPreview.title.length >= searchTextLength) && ([listingPreview.title rangeOfString:searchText].location != NSNotFound)) {
            [self.searchResults addObject:listingPreview];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*dez 8

试试这个:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Listing";
ListingPreviewTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];

// Configure the cell.
if (tableView == self.tableView) {
    cell.listingPreview = [self.listingPreviews objectAtIndex:indexPath.row];
} else {
    NSLog([[self.searchResults objectAtIndex:indexPath.row] title]);
    cell.listingPreview = [self.searchResults objectAtIndex:indexPath.row];
}

return cell;
Run Code Online (Sandbox Code Playgroud)

}

请注意,更改适用于:

ListingPreviewTableViewCell*cell = [ self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];

这样您就可以从自己的tableView中取消单元格,而不是从UISearchDisplayController创建的单元格中取消单元格.

  • 上帝祝福你.我正在敲打类似的问题. (2认同)