一、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];
[_tableView reloadData];
即可還原搜索前的數據。
另外,爲了保證健壯性,最好是在tableview的cellForRow方法中加個判斷
if (_dataArr.count > indexPath.row){
******
}