UISeachBar和委托方法

时间:2013-11-29 14:54:26

标签: ios objective-c uitableview uisearchbar

我想在一个用NSMutableArray填充的UITableView上完成一个搜索栏。问题是搜索栏委托方法显然不起作用。当我在搜索栏中输入内容时,我得不到答案,即使NSLog(@“test”)也没有触发,这让我发疯。如果我能得到任何帮助请。 (Rookie ObjC级别^^)

这是我的代码(减去所有解析xml部分): (.h)中

#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>

@interface MetamorphViewController : UITableViewController <UISearchBarDelegate, UISearchDisplayDelegate>{

    IBOutlet UITableView * newsTable;

    UISearchBar *searchBar;

    UISearchDisplayController *searchDisplayController;

    UIActivityIndicatorView * activityIndicator;

    CGSize cellSize;

    NSXMLParser * rssParser;

    NSMutableArray * stories;

    NSArray * newStories;

    NSMutableArray *filteredStories;

    NSString *dataType;

    NSString *idName;

    BOOL *uploaded;

    BOOL isFiltered;

    NSMutableDictionary * item;

    NSString * currentElement;
    NSMutableString * currentTitle, * currentDate, * currentSummary, * currentLink, * currentModule, *currentOwner, *currentOwnername;

}
- (void)parseXMLFileAtURL:(NSString *)URL typeOfModule:(NSString *)typeOfData;
@end 

(M)

- (void)viewDidLoad {
    self.navigationItem.rightBarButtonItem = self.editButtonItem;

    searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0,70,320,44)];
    [searchBar setShowsScopeBar:YES];
    [searchBar setScopeButtonTitles:[[NSArray alloc] initWithObjects:@"OBJ",@"C", nil]];

    searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
    searchDisplayController.delegate = self;
    searchDisplayController.searchResultsDataSource = self;
    [searchDisplayController setSearchResultsDelegate:self];
    self.tableView.tableHeaderView = searchBar;
    [self.tableView reloadData];
    self.tableView.scrollEnabled = YES;

}


-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    NSLog(@"test");
    //NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] %@", searchBar];
     //newStories = [stories filteredArrayUsingPredicate:filterPredicate];
    //NSLog(@"newStories %@", newStories);
}

3 个答案:

答案 0 :(得分:4)

您尚未为searchBar对象设置委托。在那之后:

[searchBar setShowsScopeBar:YES];

添加:

searchBar.delegate = self;

不要忘记添加<UISearchBarDelegate>协议。

答案 1 :(得分:1)

您是否可能忘记设置searchBar的委托。我不完全确定,但我认为searchDisplayController.delegate = self;不会这样做。

答案 2 :(得分:0)

您不需要成为UISearchBar的代表;名为searchDisplayController:shouldReloadTableForSearchString:的UISearchDisplayDelegate方法是您要实现的方法。您需要在此方法中执行的操作是根据搜索字符串过滤数据,然后返回YES以重新加载tableview。 UISearchDisplayDelegates还可以接收will / did end / begin搜索的回调,其中一些方法也可能需要实现。例如,在searchDisplayControllerWillEndSearch:中撤消数据过滤,以便在取消搜索后重新显示所有数据。