iOS 搜索框UISearchController

创建:

_searchController=[[UISearchController alloc]initWithSearchResultsController:nil];
    _searchController.hidesNavigationBarDuringPresentation = NO;
    //    _searchController.obscuresBackgroundDuringPresentation=NO;
    _searchController.searchBar.frame=CGRectMake(0,0, KSW, 44);
    _searchController.searchResultsUpdater =self;
    _searchController.searchBar.delegate=self;
    _searchController.searchBar.placeholder=@"搜索";
    _searchController.dimsBackgroundDuringPresentation=NO;
    [_searchController.searchBar sizeToFit];
    //    _searchController.searchBar.barTintColor=BG_COLOR;
    _searchController.searchBar.tintColor=C18C5A3;
    //改变背景颜色
    _searchController.searchBar.backgroundImage=[CommonTool createImageWithColor:BG_COLOR];
    
    //去黑线
    UIImageView *barImageView = [[[_searchController.searchBar.subviews firstObject] subviews] firstObject];
    barImageView.layer.borderColor = BG_COLOR.CGColor;
    barImageView.layer.borderWidth = 1;
    
    [_searchController.searchBar setImage:[UIImage imageNamed:@"Search-gray"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
    [view addSubview:_searchController.searchBar];

UISearchResultsUpdating,UISearchBarDelegate

#pragma mark -----------------搜索栏代理--------------------

-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    // 修改UISearchBar右侧的取消按钮文字颜色及背景图片
    for (id searchbuttons in [[searchBar subviews][0]subviews]) //只需在此处修改即可
        if ([searchbuttons isKindOfClass:[UIButton class]]) {
            UIButton *cancelButton = (UIButton *)searchbuttons;
            // 修改文字颜色
            [cancelButton setTitle:@"取消"forState:UIControlStateNormal];
            [cancelButton setTitleColor:C18C5A3 forState:UIControlStateNormal];
        }
}

#pragma mark  -------searchbarDelegate------
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    // 清空结果数组
    [filterArray removeAllObjects];
   
    //添加搜索条件
    NSPredicate *predicate=[NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@", _searchController.searchBar.text];
    filterArray=[[allCities filteredArrayUsingPredicate:predicate]mutableCopy];
    dispatch_async(dispatch_get_main_queue(), ^{
        [dogsTable reloadData];
    });
    
}

你可能感兴趣的:(iOS 搜索框UISearchController)