您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 教學 >> iOS 相關教學

iOS 代碼分享:正確設置 UISearchBar 的背景顏色

編輯:iOS 相關教學

今天又碰到 UISearchBar。網上流傳的老方法已經無法有效移除它的背景色了——這大概是 iOS 7 之後 UISearchBar 外觀改版造成的。目前可行的做法是直接換掉它的 backgroundImage。

// 設定背景色
mySearchBar.backgroundColor = RGBACOLOR(249, 249, 249, 1);

// 用一張透明圖換掉系統預設的背景影像
mySearchBar.backgroundImage = [self imageWithColor:[UIColor clearColor]
                                               size:mySearchBar.bounds.size];

#pragma mark - 以指定顏色產生 UIImage

- (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 決定。它內部有一層用來呈現圓角、邊框與質感的背景影像,這層影像會蓋住你設定的 backgroundColor,所以單純改背景色往往看不到效果。

因此正確思路是兩步走:先用 backgroundColor 決定底色,再用一張由程式動態產生的純色(或透明)UIImage 覆蓋掉系統那層預設影像。imageWithColor:size: 就是負責「用 Core Graphics 畫一張指定顏色的圖」的小工具。

幾個實務上的提醒

iOS 7 之後可以更省事。如果只是想去掉背景,直接把 barTintColor 設為透明、或用 searchBarStyle 搭配 UIBarStyleBlack 往往就能達到目的,不必自己產生圖片:

mySearchBar.barTintColor = [UIColor clearColor];
mySearchBar.backgroundImage = [UIImage new];   // 空的 UIImage 也管用

注意 placeholder 與游標的顏色。改了背景之後,若底色變淺而文字仍維持預設的深色,對比度可能不足。iOS 11 之後可以透過 searchTextField 直接調整文字與 icon 顏色。

UIGraphicsBeginImageContext 的替代寫法。在較新的 iOS 版本中,若只需要一張純色圖,用 UIGraphicsImageRenderer 會更簡潔,也不必手動管理 context 的 begin / end 配對:

- (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size {
    UIGraphicsImageRendererFormat *format = [[UIGraphicsImageRendererFormat alloc] init];
    format.scale = 1;
    UIGraphicsImageRenderer *renderer =
        [[UIGraphicsImageRenderer alloc] initWithSize:size format:format];
    return [renderer imageWithActions:^(UIGraphicsImageRendererContext *ctx) {
        [color setFill];
        [ctx fillRect:CGRectMake(0, 0, size.width, size.height)];
    }];
}

記得在尺寸變化時重設。imageWithColor:size: 用的是 mySearchBar.bounds.size,若 searchBar 在執行期改變了高度(例如切換橫向、或 iOS 11 之後樣式調整),這張背景圖不會自動重算。必要時在 viewDidLayoutSubviews 中重新設定一次。

簡單幾行就能擺平這個惱人的背景色問題,試試看吧。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved