将字符串传递给另一个视图

时间:2011-09-08 16:24:04

标签: objective-c

我的第一个视图中有一个UITextField接受搜索条件但是我的搜索框在我的第二个视图中。我们的想法是将用户输入的文本字段数据传递到搜索框中,该搜索框过滤第二个视图控制器中的表视图。我已经尝试设置secondviewcontroller.searchText = self.search.text但是它似乎没有使用新数据更新第二个视图控制器中的搜索框。我的代码如下:

First View.m

- (IBAction)search:(id)sender
{
    PlaceList *placelist = [[PlaceList alloc] initWithNibName:@"PlaceList" bundle:nil];

    NSLog(@"%@", search.text);

    placelist.searchBar.text = search.text;

    [self.navigationController pushViewController:placelist animated:YES];

    [placelist release]; 

}

PlaceList.m

#pragma mark UISearchBarDelegate

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    // only show the status bar’s cancel button while in edit mode
    useSearchData = YES;
    self.searchBar.showsCancelButton = YES;
    self.searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
    // flush the previous search content
    [tableData removeAllObjects];
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    self.searchBar.showsCancelButton = NO;
}

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

    if([searchText isEqualToString:@""] && [__searchBar.text isEqualToString:@""]){       //if nothing is in the search bar show normal table
        useSearchData = NO;
        [self.tableView reloadData];
        [self.searchBar resignFirstResponder];
        return;
    }
    else
    {
            searchText = __searchBar.text;

        useSearchData=YES;

        NSPredicate * p = [NSPredicate predicateWithFormat:@"name contains[cd] %@",searchText]; //comparing stored locations to searchText

        self.searchResults = [CoreDataBasicService fetchResultsForEnity:@"Place" WithPredicate:p andSortDiscriptor:@"name" Ascending:YES];

        [self.tableView reloadData];
    }
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    useSearchData = NO;

    [self.searchResults removeAllObjects];
    [self.tableView reloadData];

    [self.searchBar resignFirstResponder];
    self.searchBar.text = @"";


}

-(void)searchBarSearchButtonClicked:(UISearchBar *)_searchBar
{
    [searchBar resignFirstResponder];
}

当按下搜索IBAction时,我想推送到placeList视图并使用用户在第一个视图控制器的文本字段中输入的文本更新搜索。

提前致谢。

1 个答案:

答案 0 :(得分:1)

尝试使用搜索文本初始化PlaceList(VC),将其保存到实例变量。然后,在PlaceList(VC)的ViewDidLoad方法中,将文本设置为