如何实现AddressBook的搜索功能

时间:2016-04-05 08:40:06

标签: ios

List of contacts, bright

searchBar始终显示在self.View

点击时,就像这样:

List of a smaller number of contacts, dark

1 个答案:

答案 0 :(得分:0)

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    search =[[UISearchBar alloc]initWithFrame:CGRectMake(0, 10, 320, 44)];

    search.delegate =self;
    [self.view addSubview:search];


    arr =[[NSArray alloc]initWithObjects:@"LOVE",@"ROY",@"ROY",@"BRAZIl", nil];

    tbl =[[UITableView alloc]initWithFrame:CGRectMake(0, 60, 320, 524)];

    tbl.delegate = self;
    tbl.dataSource =self;


    [self.view addSubview:tbl];
}

//表格视图

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (isFilter)
    {
        return arr1.count;
    }
    return arr.count;

}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell1"];
   // cell =[arr objectAtIndex:indexPath.row];
    if (isFilter)
    {
        cell.textLabel.text = [arr1 objectAtIndex:indexPath.row];
    }
    else
    {

    cell.textLabel.text =[arr objectAtIndex:indexPath.row];
    }
    return cell;


}

//搜索栏委托

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
// return NO to not become first responder
    return YES;

}
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    // return NO to not resign first responder

    return YES;
}


- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
// called when text starts editing


}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
// called when text ends editing

}


- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    // called when keyboard search button pressed

    [search resignFirstResponder];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
// called when text changes (including clear)

    arr1 =[[NSMutableArray alloc]init];
    if (searchText.length == 0)
    {
        isFilter = NO;

    }
    else
    {
        isFilter = YES;
    }

    for (int i = 0; i<arr.count; i++)
    {
        NSString *str =[arr objectAtIndex:i];

        NSRange range =[str rangeOfString:searchText options:NSCaseInsensitiveSearch];

        if (range.length>0)
        {
            [arr1 addObject:str];
        }
    }
    [tbl reloadData];
}

尝试搜索栏。