UISearchBar 暴露的公開屬性其實很有限——barStyle、text、placeholder、tintColor 這些顯然撐不起設計稿的要求。想改 placeholder 顏色、換輸入框背景圖、替換左側放大鏡圖標,就只能往下鑽一層。本文給出幾種可複用的做法。
把定制邏輯收進子類的 layoutSubviews,使用起來最省心。新建 LSSearchBar:
// LSSearchBar.h #import <UIKit/UIKit.h> @interface LSSearchBar : UISearchBar @end
// LSSearchBar.m
#import "LSSearchBar.h"
@implementation LSSearchBar
- (void)layoutSubviews
{
[super layoutSubviews];
// 通過遍歷 self.subviews 找到內部的 searchField
UITextField *searchField;
NSUInteger numViews = [self.subviews count];
for (int i = 0; i < numViews; i++) {
if ([[self.subviews objectAtIndex:i] isKindOfClass:[UITextField class]]) {
searchField = [self.subviews objectAtIndex:i];
}
}
// 若第一層找不到(部分系統版本多包了一層容器),再往下鑽一層
if (searchField == nil) {
NSArray *arraySub = [self subviews];
UIView *viewSelf = [arraySub objectAtIndex:0];
NSArray *arrayView = [viewSelf subviews];
for (int i = 0; i < arrayView.count; i++) {
if ([[arrayView objectAtIndex:i] isKindOfClass:[UITextField class]]) {
searchField = [arrayView objectAtIndex:i];
}
}
}
if (!(searchField == nil)) {
// 文字顏色
searchField.textColor = [UIColor whiteColor];
// 背景圖 + 去掉系統默認邊框
[searchField setBackground:[UIImage imageNamed:@"searchbar"]];
[searchField setBorderStyle:UITextBorderStyleNone];
// placeholder 顏色(利用 KVC 訪問私有鍵)
[searchField setValue:[UIColor whiteColor]
forKeyPath:@"_placeholderLabel.textColor"];
// 替換左側放大鏡圖標
UIImage *image = [UIImage imageNamed:@"search"];
UIImageView *iView = [[UIImageView alloc] initWithImage:image];
iView.frame = CGRectMake(0, 0, 15, 15);
searchField.leftView = iView;
}
}
@end
為什麼要寫兩層遍歷?因為不同 iOS 版本中 UISearchBar 的內部視圖層級並不一致:早期 UITextField 直接掛在 searchBar 下,後來被包進了一個額外的容器 view。兩段遍歷一起寫,兼容性更好。
UISearchBar 由兩個 subview 組成:UISearchBarBackground 和 UITextField。IB 裡沒有直接操作背景的屬性,最直接的做法是把背景層移除:
seachBar = [[UISearchBar alloc] init];
seachBar.backgroundColor = [UIColor clearColor];
for (UIView *subview in seachBar.subviews) {
if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
[subview removeFromSuperview];
break;
}
}
for (UIView *subView in self.searchBar.subviews) {
for (UIView *secondLevelSubview in subView.subviews) {
if ([secondLevelSubview isKindOfClass:[UITextField class]]) {
UITextField *searchBarTextField = (UITextField *)secondLevelSubview;
searchBarTextField.textColor = [UIColor blackColor]; // 在此設置顏色
break;
}
}
}
從 iOS 7 開始,UIView 引入了 tintColor 這套「著色鏈」機制,子視圖會沿著層級繼承父視圖的 tint。因此:
tintColor 用於給前景元素著色(文字、光標、按鈕);barTintColor 用於給欄本身背景著色。這兩者都是公開 API,優先在 iOS 7 及以上使用。
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil]
setTextColor:[UIColor blueColor]];
這裡有個容易被誤解的地方:UIAppearance 協議本身是公開 API,但 UITextField 並未聲明支持它。翻一下 UITextField.h 會發現裡面沒有任何 UI_APPEARANCE_SELECTOR 標記(對比 UIButton 就有很多)。所以上面這行代碼並非官方保證行為,在系統升級後可能失效,不建議作為主要方案。
- (void)setTextColor:(UIColor *)color
{
for (UIView *v in self.subviews) {
if ([Environment isVersion7OrHigher]) // 依據 UIDevice#systemVersion 判斷
{
for (id subview in v.subviews) {
if ([subview isKindOfClass:[UITextField class]]) {
((UITextField *)subview).textColor = color;
}
}
}
else
{
if ([v isKindOfClass:[UITextField class]]) {
((UITextField *)v).textColor = color;
}
}
}
}
把版本判斷與遍歷邏輯一次性封裝好,業務代碼裡只需 [searchBar setTextColor:[UIColor whiteColor]],可讀性和可維護性都更好。
- (void)layoutSubviews
{
UITextField *searchField;
NSUInteger numViews = [self.subviews count];
for (int i = 0; i < numViews; i++) {
if ([[self.subviews objectAtIndex:i] isKindOfClass:[UITextField class]]) {
searchField = [self.subviews objectAtIndex:i];
}
}
if (!(searchField == nil)) {
searchField.textColor = [UIColor whiteColor];
[searchField.leftView setHidden:YES]; // 隱藏默認放大鏡
[searchField setBackground:[UIImage imageNamed:@"SearchBarBackground.png"]];
[searchField setBorderStyle:UITextBorderStyleNone];
}
[super layoutSubviews];
}
必須坦白說清楚:本文涉及的所有「鑽進 subviews 找 UITextField」的技術,本質上都是私有視圖層級黑科技。蘋果從未承諾 UISearchBar 的內部結構穩定,這也解釋了為什麼同一份代碼要寫兩層遍歷來兼容不同版本。使用 setValue:forKeyPath:@"_placeholderLabel.textColor" 這類 KVC 訪問私有鍵,更有被審核或系統升級打回的風險。
如果項目 targeting iOS 8 以上,強烈建議改用 UISearchController。它把搜索框、結果展示、與原頁面滾動的互斥行為一起封裝好了,而且從 iOS 11 起蘋果開始逐步收緊對私有 API 的容忍度,公開路徑不僅更安全,長期維護成本也低得多。