從上圖能夠看出,咱們要作的UISearchBar要有圓角,邊框顏色,取消按鈕顏色,背景透明等等。git
開始覺得可能要本身寫一個自定義的UISearchBar控件了,後面研究了一番,發現能夠設定系統UISearchBar屬性來更改,便把經驗記錄下來。github
首先,咱們看下系統默認的SearchBar的樣式,離咱們的目標樣式確實相差很大, 後面我會一步一步詳細說明作成咱們的目標樣式。app
我以白色的背景色爲例,下面看看代碼:字體
//1. 設置背景顏色 //設置背景圖是爲了去掉上下黑線 self.customSearchBar.backgroundImage = [[UIImage alloc] init]; // 設置SearchBar的顏色主題爲白色 self.customSearchBar.barTintColor = [UIColor whiteColor];
//2. 設置圓角和邊框顏色 UITextField *searchField = [self.customSearchBar valueForKey:@"searchField"]; if (searchField) { [searchField setBackgroundColor:[UIColor whiteColor]]; searchField.layer.cornerRadius = 14.0f; searchField.layer.borderColor = [UIColor colorWithRed:247/255.0 green:75/255.0 blue:31/255.0 alpha:1].CGColor; searchField.layer.borderWidth = 1; searchField.layer.masksToBounds = YES; }
這段代碼有個特別的地方就是經過KVC得到到UISearchBar的私有變量
searchField(類型爲UITextField),設置SearchBar的邊框顏色和圓角實際上也就變成了設置searchField的邊框顏色和圓角,你能夠試試直接設置SearchBar.layer.borderColor和cornerRadius,會發現這樣作是有問題的。ui
嗯,離預期效果愈來愈近了,有木有!spa
//3. 設置按鈕文字和顏色 [self.customSearchBar fm_setCancelButtonTitle:@"取消"]; self.customSearchBar.tintColor = [UIColor colorWithRed:86/255.0 green:179/255.0 blue:11/255.0 alpha:1]; //修正光標顏色 [searchField setTintColor:[UIColor blackColor]]; //其中fm_setCancelButtonTitle是我寫的UISearchBar一個分類的方法 - (void)fm_setCancelButtonTitle:(NSString *)title { if (IS_IOS9) { [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTitle:title]; }else { [[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitle:title]; } }
須要特別注意的是設置searchBar的tintColor會使輸入框的光標顏色改變,能夠經過設置searchField的tintColor來修正。設計
//4. 設置輸入框文字顏色和字體 [self.customSearchBar fm_setTextColor:[UIColor blackColor]]; [self.customSearchBar fm_setTextFont:[UIFont systemFontOfSize:14]]; //下面兩個方法是UISearchBar分類代碼 - (void)fm_setTextColor:(UIColor *)textColor { if (IS_IOS9) { [UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]].textColor = textColor; }else { [[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:textColor]; } } - (void)fm_setCancelButtonTitle:(NSString *)title { if (IS_IOS9) { [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTitle:title]; }else { [[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitle:title]; } }
下面評論中有簡友問我怎麼更改默認的搜索圖標,我查了下UISearchBar的API,發現有方法能夠更改的。3d
//5. 設置搜索Icon [self.customSearchBar setImage:[UIImage imageNamed:@"Search_Icon"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
爲了跟系統默認Icon的有個明顯的對比,我特殊找了張綠色的搜索Icon,效果見下圖:code
Tips: 還能夠設置其餘的Icon(如清除按鈕圖標),也是用上面的方法,具體要設置什麼,能夠去看看UISearchBarIcon這個枚舉。orm
很簡單,在storyboard中設置searchBar的Bar Style爲Minimal,或者用代碼設置 :
//設置相似QQ搜索框 self.minimalSearchBar.searchBarStyle = UISearchBarStyleMinimal;
完整代碼在這裏。