以前常見的做法是直接設定 UISearchBar 的 backgroundImage 或找它的 subview 來改色,但在較新的 iOS 版本上已經不再有效。目前比較可靠的方式是自己產生一張純色圖片,塞給 backgroundImage。
mySearchBar.backgroundColor = RGBACOLOR(249, 249, 249, 1);
mySearchBar.backgroundImage = [self imageWithColor:[UIColor clearColor] size:mySearchBar.bounds.size];
// 以指定顏色產生一張純色圖片
- (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;
}
原理是:UISearchBar 的背景並非由 backgroundColor 直接決定,而是由 backgroundImage 覆蓋上去,所以改 backgroundColor 只會影響邊緣。把 backgroundImage 換成一張透明圖,原本的背景就被蓋掉了。
實務上有幾個細節:一是上面範例同時設了 backgroundColor 與透明 backgroundImage,前者決定最終看起來的顏色,後者負責消除系統預設的漸層;二是若還想改輸入框本身(那個圓角內框)的顏色,需要另外設定 searchBar.searchBarStyle,或用 for loop 找出 UITextField 子視圖後設定其 backgroundColor,但後者依賴私有視圖結構,系統更新後可能失效;三是 iOS 13 之後建議改用 searchTextField 這個公開屬性來調整文字框樣式,比遍歷 subviews 安全得多。