//创建搜索按钮
self.searchBar= [[UISearchBaralloc]initWithFrame:CGRectMake(8,8,screenWith-16,44)];
self.searchBar.barTintColor=UIColorFromRGBA(216,160,116,1);
self.searchBar.searchBarStyle=UISearchBarStyleDefault;
self.searchBar.returnKeyType=UIReturnKeySearch;
self.searchBar.layer.cornerRadius=8;
self.searchBar.layer.masksToBounds=YES;
self.searchBar.placeholder=@"请输入关键词";
[self.searchBarsetImage:[UIImageimageNamed:@"yiunion_search box"]forSearchBarIcon:UISearchBarIconSearchstate:UIControlStateNormal];
//找到searchbar的searchField属性
UITextField*searchField = [self.searchBarvalueForKey:@"searchField"];
if(searchField) {
//背景色
[searchFieldsetBackgroundColor:[UIColorwhiteColor]];
//设置字体颜色&占位符(必须)
searchField.textColor= [UIColorblackColor];
//根据@"_placeholderLabel.textColor"找到placeholder的字体颜色
[searchFieldsetValue:UIColorFromRGBA(235,219,206,1)forKeyPath:@"_placeholderLabel.textColor"];
}
[self.searchBarsetShowsCancelButton:YES];
[self.searchBarbecomeFirstResponder];
//设置代理
self.searchBar.delegate=self;
#pragma mark - searchBar delegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar*)searchBar_ {
//对取消文字作国际化(必须要在这个代理方法里面进行设置,同时要设置cancel按钮在此代理里才开始显示)
UIView*topView = searchBar_.subviews[0];
for(UIView*subViewintopView.subviews) {
if([subViewisKindOfClass:NSClassFromString(@"UINavigationButton")]) {
UIButton*cancelButton = (UIButton*)subView;
[cancelButtonsetTitle:AppLocalizedString(@"Cancel")forState:UIControlStateNormal];
[cancelButtonsetTitleColor:UIColorFromRGBA(216,160,116,1)forState:UIControlStateNormal];
break;
}
}
returnYES;
}
/**
*开始搜索
*
*@param searchBar searchBar description
*/
- (void)searchBarSearchButtonClicked:(UISearchBar*)searchBar{
[searchBarresignFirstResponder];
//取消按钮在UISearchBar失去焦点之后,其enabled属性为no,导致失去焦点之后,你再点击取消按钮,此时就不执行searchBarCancelButtonClicked。而是先获得焦点,然后你再点击,才执行到searchBarCancelButtonClicked。即点两次才能触发到searchBarCancelButtonClicked函数。
UIView*topView = searchBar.subviews[0];
for(UIView*subViewintopView.subviews) {
if([subViewisKindOfClass:NSClassFromString(@"UINavigationButton")]) {
UIButton*cancelButton = (UIButton*)subView;
cancelButton.enabled=YES;
break;
}
}
.......
}
- (void)searchBarCancelButtonClicked:(UISearchBar*)searchBar{
[searchBarresignFirstResponder];
if(self.navigationController.presentingViewController) {
[selfdismissViewControllerAnimated:YEScompletion:nil];
}
elseif([self.navigationController.viewControllerscount] >1)
{
[self.navigationControllerpopViewControllerAnimated:YES];
}
}