Как добавить панель поиска и отображение поиска в RSS-канал в UItableview

Я создал программу для чтения RSS, которая анализирует XML-файл. Я пытаюсь создать панель поиска и контроллер отображения поиска, но я не уверен, как искать objectForKey "title" или objectForKey "summary" в UITableView.

Любая помощь будет принята с благодарностью.

NumberOfRowsInSection и cellForRowAtIndexPath выглядят так:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return self.parseResults.count;
}

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

    //Check if cell is nil. If it is create a new instance of it
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
    // Configure titleLabel
    cell.textLabel.text = [[self.parseResults objectAtIndex:indexPath.row] objectForKey:@"title"];
    cell.textLabel.numberOfLines = 2;
    //Configure detailTitleLabel
     cell.detailTextLabel.text = [[self.parseResults objectAtIndex:indexPath.row] objectForKey:@"summary"];

    cell.detailTextLabel.numberOfLines = 2;

    //Set accessoryType
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    //Set font and style
     cell.selectionStyle = UITableViewCellSelectionStyleGray;
     cell.textLabel.font = [UIFont boldSystemFontOfSize:14];

    return cell;
}

Я недавно пытался следовать этому примеру проекта - https://github.com/deepthit/TableViewSearch.git - на основе предложения.
Мой код тогда выглядел так:

@interface QldRecentJudgmentsViewController () {

    __strong NSArray *mFilteredArray_;
    __strong UISearchBar *mSearchBar_;
    __strong UISearchDisplayController *mSearchDisplayController_;
}

@end

 @implementation ViewController
 @synthesize parseResults = _parseResults, HUD;


- (void)viewDidLoad {
    [super viewDidLoad];


    mSearchBar_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0,
                                                            0,
                                                            self.view.bounds.size.width,
                                                            44)];

     mSearchBar_.delegate = self;
     mSearchBar_.placeholder = @"search";
     self.tableView.tableHeaderView = mSearchBar_;

     mSearchDisplayController_ = [[UISearchDisplayController alloc] initWithSearchBar:mSearchBar_
                                                              contentsController:self];
     mSearchDisplayController_.searchResultsDelegate = self;
     mSearchDisplayController_.searchResultsDataSource = self;
     mSearchDisplayController_.delegate = self;

 }



#pragma mark - Table view data source

 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
 }

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    //return self.parseResults.count;

    if (tableView == self.searchDisplayController.searchResultsTableView ||
    [mFilteredArray_ count] > 0)
    {
        return [mFilteredArray_ count];
    }
    return parseResults.count;

}


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

    id result;
    if (tableView == self.searchDisplayController.searchResultsTableView ||
    [mFilteredArray_ count] > 0)
    {
        result = [mFilteredArray_ objectAtIndex:indexPath.row];
    }
    else
    {
        result = [parseResults objectAtIndex:indexPath.row];
    }


    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    //Check if cell is nil. If it is create a new instance of it
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];

        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    }
    // Configure titleLabel
    cell.textLabel.text = [[self.parseResults objectAtIndex:indexPath.row] objectForKey:@"title"];
    cell.textLabel.numberOfLines = 2;
    //Configure detailTitleLabel
    cell.detailTextLabel.text = [[self.parseResults objectAtIndex:indexPath.row] objectForKey:@"summary"];

    cell.detailTextLabel.numberOfLines = 2;

    //Set accessoryType
    //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    //Set font and style
    cell.selectionStyle = UITableViewCellSelectionStyleGray;
    cell.textLabel.font = [UIFont boldSystemFontOfSize:14];

    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *url = [[self.parseResults objectAtIndex:indexPath.row] objectForKey:@"link"];
    NSString *title = [[self.parseResults objectAtIndex:indexPath.row] objectForKey:@"title"];
    WebViewController *viewController = [[WebViewController alloc] initWithURL:url title:title];
    [self.navigationController pushViewController:viewController animated:YES];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

}

#pragma mark - UISearchBarDelegate

- (void)searchBar:(UISearchBar *)searchBar
textDidChange:(NSString *)searchText {
    if ([searchText length] == 0)
    {
        [self.tableView reloadData];
        return;
    }

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.title contains[cd] %@ OR SELF.summary contains[cd] %@", searchText, searchText];
    mFilteredArray_ = [self.parseResults filteredArrayUsingPredicate:predicate];

    [self.tableView reloadData];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    mFilteredArray_ = nil;
    [self.tableView reloadData];
}

Однако, когда я прослеживаю это, лента RSS больше не загружается в виде таблицы, поэтому результатов нет. Тем не менее, когда я пытаюсь выполнить поиск, он неправильно выполняет поиск в "заголовке" или "сводке", и результаты поиска отображаются некорректно - ячейки не выровнены аккуратно после поиска чего-либо и получения результатов. Кроме того, единственный способ увидеть RSS в табличном представлении - это поиск любой общей строки, но после нажатия кнопки "Отмена" в строке поиска RSS-канал исчезает и отображает пустое табличное представление.

Спасибо за любую помощь заранее.

0 ответов

Другие вопросы по тегам