UISearchBarのカスタマイズでいろいろ苦戦したので記録を残しておこうと思います。
フォントの色を変更する
# UISearchBarのUITextFieldを取得する
UITextField *searchField = [self.searchBar valueForKey:@"_searchField"];
searchField.textColor = [UIColor whiteColor];
UISearchBarにはtintColorというプロパティがありますが、これを設定してもフォントの色は変わりません。
UISearchBarのサブビューのUITextFieldを取得して設定を行います。
プレースホルダーのフォントの色を変更する
# UISearchBarのplaceholderを設定
UISearchBar *searchBar = [[UISearchBar alloc] init];
searchBar.placeholder = @"placeholder text";
# UISearchBarのUITextFieldを取得する
UITextField *searchField = [self.searchBar valueForKey:@"_searchField"];
searchField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:searchBar.placeholder attributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
プレースホルダーのフォントの色を変更する場合もUITextFieldを取得する必要があります。
initWithString:attributes:のinitWithStringにはプレースホルダーに設定するテキストを指定します。
2箇所にプレースホルダーテキストを設定しているため、initWithString:attributes:だけでいい気もしますが、これだけだとプレースホルダーが表示されません。
アイコンを変更する
# 虫眼鏡アイコンを変更
UIImage *searchIcon = [UIImage imageNamed:@"search"];
[self.searchBar setImage:searchIcon forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
# クリアボタンを変更
searchIcon = [UIImage imageNamed:@"search_remove"];
NSData* searchIconData = [[NSData alloc] initWithData:UIImagePNGRepresentation(searchIcon)];
searchIcon = [[UIImage alloc] initWithData:searchIconData scale:5];
[self.searchBar setImage:searchIcon forSearchBarIcon:UISearchBarIconClear state:UIControlStateNormal];
アイコンを変更する場合は、UISearchBarのsetImage:forSearchBarIcon:state:UIControlStateNormalで設定します。
UIImageを作成して、アイコンと状態(highlightとかselectedとか)を選択して設定します。
クリアボタンの設定時にわざわざNSDataに変換してからUIImageに戻すというなんとも無駄そうなことをしていますが、クリアボタンを設定すると下の画像のようにサイズが合いません。
そこでinitWithData:scale:を使って画像のscaleを調整することで、丁度良いサイズで表示されるように設定しています。
追記
サイズがおかしくなるのはUIControlStateNormalのときだけみたいです。
UIControlStateHighlightedにscaleを変更した画像を設定しても反映されませんでした。
UIControlStateHighlightedにはscaleを変更する前の画像するようにしましょう。
まとめ
UISearchBarのカスタマイズといってもフォントの色とかアイコンを変更するなどたいしたことではありませんが、思ったよりもサクッとできるようにできていません。UITextFieldを取得するにもプロパティとして定義されていないため、上記のような方法で取得するしかありません。
間違いなどもっと簡単にできるなどありましたら教えていただけるとうれしいです。
参考
UISearchBar Class Reference
UIImage Class Reference
UISearchBar change placeholder color