UISearchBar使用prepareForSegue

时间:2013-02-19 00:44:52

标签: ios search searchbar

我正在做一个小项目,但我遇到了问题。我有一个带UISearcBar的UITableView。一切正常,搜索给我正确的结果,但现在我想使用prepareForSegue方法,以便为每个搜索结果转到detailViewController。

例如。如果我搜索产品“A”,并找到它,当选择该产品时,它会用于ViewController_A,如果我搜索并选择产品“B”,它应该用于ViewControler_B。

此时此代码没有我选择的代码,它总是转到同一个Viewcontroller。

#pragma mark - TableView Delegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Perform segue to candy detail
    [self performSegueWithIdentifier:@"candyDetail" sender:tableView];


}

#pragma mark - Segue
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([[segue identifier] isEqualToString:@"candyDetail"]) {
        UIViewController *candyDetailViewController = [segue destinationViewController];



        // In order to manipulate the destination view controller, another check on which table (search or normal) is displayed is needed
        if(sender == self.searchDisplayController.searchResultsTableView) {
            NSIndexPath *indexPath = [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow];
            NSString *destinationTitle = [[filteredCandyArray objectAtIndex:[indexPath row]] name];
            [candyDetailViewController setTitle:destinationTitle];
        }
        else {
            NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
            NSString *destinationTitle = [[candyArray objectAtIndex:[indexPath row]] name];
            [candyDetailViewController setTitle:destinationTitle];
        }

    }
        }

1 个答案:

答案 0 :(得分:0)

那是因为你总是调用相同的segueId,“candyDetail”。

相反,你应该在你的UIStoryBoard中连接两个手动segue,每个都指向不同的场景(一个id为“showViewControllerA”到ViewControllerA,另一个“showViewControllerB”指向ViewControllerB)。然后,您可以执行以下操作:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([[self.candyArray objectAtIndex:indexPath.row] isKindOfClass:[CandyA class]]) {
        [self performSegueWithIdentifier:@"showViewControllerA" sender:self];
    } else if ([[self.candyArray objectAtIndex:indexPath.row] isKindOfClass:[CandyB class]]) {
        [self performSegueWithIdentifier:@"showViewControllerB" sender:self];
    };
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"showViewControllerA"]) {
        ViewControllerA *viewControllerA = [segue destinationViewController];
        // configure viewControllerA here...
    } else if ([[segue identifier] isEqualToString:@"showViewControllerA"]) {
        ViewControllerB *viewControllerB = [segue destinationViewController];
        // configure viewControllerB here...
    }
}

另一种选择是您可以将动作segue直接连接到不同的单元格,并根据源数组中的糖果类型切换您在-tableView:cellForRowAtIndexPath:中出列的单元格类型。无论哪种方式,你都需要两个指向不同场景的segue。