UISearchDisplayController 和 UISearchBar

一、UISearchBar 的界面

   1、屬性searchBarStyle對應的界面

   2、設置UISearchBar的背景色

     代碼:

      searchBar.backgroundColor = [UIColor blackColor];

     效果:

    


    如果想設置默認情況下的背景色,則可以通過設置背景圖片來實現

    先添加方法:

    

- (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size

{

    CGRect rect = CGRectMake(0, 0, size.width, size.height);

    UIGraphicsBeginImageContext(rect.size);

    CGContextRef context = UIGraphicsGetCurrentContext();

    

    CGContextSetFillColorWithColor(context, [color CGColor]);

    CGContextFillRect(context, rect);

    

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    

    return image;

}

    再添加代碼:

    searchBar.backgroundImage = [self imageWithColor:[UIColor blackColor] size:searchBar.bounds.size];

    

   

   2、設置UISearchBar的文字的顏色

   方法一:

        

     for (UIView *subView in self.searchBar.subviews)

     {

        for (UIView *secondLevelSubview in subView.subviews){

            if ([secondLevelSubview isKindOfClass:[UITextField class]])

            {

                UITextField *searchBarTextField = (UITextField *)secondLevelSubview;

                //set font color here

                searchBarTextField.textColor = [UIColor colorWithWhite:0.799 alpha:1.000];

                break;

            }

        }

     }

    方法二:

 [[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:[UIColor whiteColor]];


一、UISearchDisplayController用法

  

    mySearchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];

    mySearchDisplayController.delegate = self;

    mySearchDisplayController.searchResultsDataSource = self;

    mySearchDisplayController.searchResultsDelegate = self;


   

注:UISearchDisplayController 的結果顯示依賴於他的代理的tableView樣式,在searchBar的代理方法中直接對數據源的數據進行改變。最後重新加載數據

    [mySearchDisplayController.searchResultsTableView reloadData];


UISearchDisplayController將要消失的時候,把之前的數據重新賦值給數據源調用

    [_tableView reloadData];

即可還原搜索前的數據。

另外,爲了保證健壯性,最好是在tableview的cellForRow方法中加個判斷

  if (_dataArr.count > indexPath.row){

      ******     

  }














  


發佈了61 篇原創文章 · 獲贊 2 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章