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

UISearchBar 客製化實戰:改 placeholder 顏色、背景與搜尋圖示

編輯:iOS 相關教學

UISearchBar 是 iOS 開發常見的元件之一,打開來看有 barStyle、text、placeholder 等屬性。但這些內建屬性顯然不足以應付所有設計稿——例如改 placeholder 顏色、換 UITextField 背景、替換輸入框上的小圖示等等。

要滿足這些需求,比較乾淨的做法是寫一個子類,這裡取名 LSSearchBar。

建立 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];
        }
    }

    // 若上述方法找不到,試試多一層的情況(iOS 7 之後的結構)
    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 顏色
        [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

改 UISearchBar 的背景顏色

UISearchBar 由兩個 subview 組成:一個是 UISearchBarBackground,另一個是 UITextField。IB 沒有直接操作背景,因此做法是直接把 UISearchBarBackground 移掉:

seachBar = [[UISearchBar alloc] init];
seachBar.backgroundColor = [UIColor clearColor];
for (UIView *subview in seachBar.subviews) {
    if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
        [subview removeFromSuperview];
        break;
    }
}

改文字顏色

iOS 7 之後,UITextField 的層級往下移了一層,所以要再多跑一層迴圈:

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;
        }
    }
}

另外,也可以改用 tintColor 為前景上色,用 barTintColor 為欄位背景上色。從 iOS 7 起,UIView 都支援 tintColor 的行為。

关于 UIAppearance 的注意事項

網路上常見這種寫法:

[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:[UIColor blueColor]];

但要留意:UITextField 其實並未正式支援 UIAppearance 的這個用法(翻一下 UITextField.h 找不到 UI_APPEARANCE_SELECTOR 標記即可證實),所以這段程式並不總是有效。

比較可靠的做法是手動遍歷子檢視設定,或者寫一個分類:

- (void)setTextColor:(UIColor *)color
{
    for (UIView *v in self.subviews) {
        if ([Environment isVersion7OrHigher]) {
            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;
            }
        }
    }
}

自訂背景圖

- (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];
}

最後提醒:透過 KVC 存取 _placeholderLabel.textColor 這種私有介面,在版本更新時有失效風險,正式專案若要用,建議包一層判斷並做好降級處理。

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