本人在工作之余需要使用UISearchBar,發(fā)現(xiàn)看似一個小小的搜索框其實還是有很多麻煩之處,尤其是在ios7以后爹土,自己在網(wǎng)上找了很多但很多都不行或者沒有用甥雕,今天在此小總結(jié)一下搜索框的用法。
- 添加兩個數(shù)組胀茵,一個UISearchController
@property(nonatomic,retain)UISearchController *searchController;
@property(nonatomic,retain)NSMutableArray *searchResults;//接收數(shù)據(jù)源結(jié)果
@property(nonatomic,retain)NSArray * dibiaoArr;//原始數(shù)據(jù)
- 創(chuàng)建UISearchBar(添加代理UISearchBarDelegate)
//搜索框
self.searchController = [[UISearchController alloc]initWithSearchResultsController:nil];
_searchController.searchBar.frame = CGRectMake(10, 10, screen_width-20, 40);
self.searchController.dimsBackgroundDuringPresentation = false;
_searchController.searchBar.delegate = self;
//按鈕字體顏色
_searchController.searchBar.tintColor = RGBColor(183, 142, 68, 1.0);
//改變搜索框外部框的顏色(需要隱藏background才能顯示背景色)
_searchController.searchBar.backgroundImage = [self imageWithColor:[UIColor clearColor] size:_searchController.searchBar.bounds.size];
//水印
_searchController.searchBar.placeholder = @"請輸入地址";
[_searchController.searchBar sizeToFit];
self.searchController.searchResultsUpdater = self;
//用textfiled代替搜索框
UITextField *searchField=[_searchController.searchBar valueForKey:@"_searchField"];
searchField.backgroundColor = RGBColor(40, 39, 44, 1.0);
//水印顏色
[searchField setValue:RGBColor(137, 136, 140, 1.0) forKeyPath:@"_placeholderLabel.textColor"];
//搜索欄表頭視圖
self.tableView.tableHeaderView = _searchController.searchBar;
self.dibiaoArr = @[@"下想",@"查快遞"];
- 效果如圖
50FBB2CA-6137-44FA-ABAC-1A096B5EFAB7.png
這里很多人在修改搜索框的外框背景顏色社露,用了backgroundColor 但是沒什么反應(yīng),通過debug可以看到這里多了一層view琼娘,然后將設(shè)置的顏色遮蓋掉了峭弟。內(nèi)部框的屬性直接修改textfiled就可以了,外部框需要注意.
- 以為這樣設(shè)置就可以了脱拼,結(jié)果點擊編輯搜索框的背景顏色又改變了瞒瘸。這時候需要去代理方法:-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar添加屬性。
searchBar.barTintColor = RGBColor(40, 39, 44, 1.0);
// 修改UISearchBar右側(cè)的取消按鈕文字顏色及背景圖片
for (id searchbuttons in [[_searchController.searchBar subviews][0]subviews]) //只需在此處修改即可
if ([searchbuttons isKindOfClass:[UIButton class]] ) {
[cancelButton setTitle:@"取消"forState:UIControlStateNormal];
[cancelButton setTitle:@"取消"forState:UIControlStateSelected];
[cancelButton setTitleColor:RGBColor(183, 142, 68, 1.0) forState:UIControlStateNormal];
[cancelButton setTitleColor:RGBColor(183, 142, 68, 1.0) forState:UIControlStateHighlighted];
}
- 然而到這里熄浓,發(fā)現(xiàn)還是有問題情臭,就是第一次進入編輯時,取消按鈕的字體沒有改變赌蔑,再進入第二次的時候卻改變了俯在,說明當?shù)谝淮芜M入編輯狀態(tài)時,取消按鈕根本還沒有被加載惯雳,在這里我使用的是延遲1秒后再進行查找朝巫,等按鈕加載出來后再執(zhí)行方法鸿摇。這樣就沒問題了石景。
- 效果如圖
86195412-8385-40F0-B2E7-990DFB7A3515.png