在 iOS 開發中,UISearchBar 預設自帶一層灰色的背景樣式,這在很多需要與頁面融合的設計裡顯得格格不入。想讓搜索框看起來「無縫」地融入背景,最常見的做法就是把它換成一張透明的背景圖。下面分享一個實用的小技巧。
核心思路是:並非直接修改某個背景色屬性,而是動態生成一張指定尺寸、指定顏色的 UIImage,再把它賦給 searchBar.backgroundImage。這樣一来,背景就被我們完全掌控了。
// 搜索條的背景色
self.search.backgroundImage = [self imageWithColor:[UIColor colorWithRed:237/255.0 green:237/255.0 blue:237/255.0 alpha:0] size:_search.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;
}
這段代碼的關鍵在於 alpha:0,也就是完全透明的通道值。當你把生成的透明圖片設為背景後,搜索框原有的灰色底紋便會消失。如果想改成半透明或自訂顏色,只需調整 colorWithRed:green:blue:alpha: 的參數即可,非常靈活。