UITableView搜索栏问题

时间:2012-03-18 14:20:43

标签: iphone ios5 tableview searchbar

我有一个表格视图,里面有一个搜索栏。我似乎正确地编写了代码,但是当我在搜索栏中输入内容时,没有结果(即使应该有)。

@interface PlaylistViewController : UITableViewController 
<UITableViewDelegate,UITableViewDataSource, UISearchBarDelegate>


@property (strong, nonatomic) Playlist* playlistTab;
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property (strong, nonatomic) NSMutableArray *displayItems;

@end


@implementation PlaylistViewController 
@synthesize searchBar = _searchBar;
@synthesize tableView = _tableView;
@synthesize playlistTab = _playlistTab;
@synthesize displayItems = _displayItems;

- (void)viewDidLoad
{
    [super viewDidLoad];

    AppDelegate *appDel = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [self setPlaylistTab:appDel.playlist];
    _displayItems = _playlistTab.collection;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_displayItems count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"songCell"];
    Song* song = [_displayItems objectAtIndex:indexPath.row];
    cell.textLabel.text = song.title;
    cell.detailTextLabel.text = song.artist;

    return cell;
}

-(void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    if ([searchText length]==0) {
        [_displayItems removeAllObjects];
        [_displayItems addObjectsFromArray:_playlistTab.collection];
    } else {
        [_displayItems removeAllObjects];
        for (Song *song in _playlistTab.collection) {
            NSRange rangeTitle = [song.title rangeOfString:searchText     options:NSCaseInsensitiveSearch];
            // NSRange rangeArtist = [song.artist rangeOfString:searchText options:NSCaseInsensitiveSearch];
            if (rangeTitle.location != NSNotFound) {
                [_displayItems addObject:song];
            }
        }
    }

    [self.tableView reloadData];
}

为了让这项工作正常,我该怎么做?

1 个答案:

答案 0 :(得分:1)

虽然这几乎相同,但试试这个

 for(int i=0;i<[_playlistTab.collection count];i++){
      NSLog(@"entered here 1");
      Song *song = (Song *)[_playlistTab.collection objectAtIndex:i];
      NSRange rangeTitle = [song.title rangeOfString:searchText     options:NSCaseInsensitiveSearch];
      NSLog(@"%@",rangeTitle);
      if(rangeTitle.length != 0) {
          NSLog(@"entered here 2");
          [_displayItems addObject:song];
      }
}