2011-08-29 20 views
7

UISearchBarの入力フィールドの背景色を変更しようとしています。これは、検索するテキストを入力する丸みのあるビューです。デフォルトの色は白です。私が試したUISearchBar:入力フィールドの背景色を変更する

をグレーにそれを変更したいと思います:

for (UIView *subView in searchBar.subviews) { 
    if ([subView isKindOfClass:NSClassFromString(@"UITextField")]) { 
     UITextField *textField = (UITextField *)subView; 
     [textField setBackgroundColor:[UIColor grayColor]]; 
    } 

しかし、それは動作しません:(

私もテキストフィールドに画像ビューを挿入しようとしたが、それは丸みを帯びたビューを思わテキストフィールドから独立しているので、いずれかの手がかり機能で

+0

uがなければなりませんinterfacebuilder.iにないコードで検索バーを作成する際にIB.soから作成中に同じ問題が発生しましたあなたの応答のために検索バー –

+0

に感謝します。私はそれを試してみます – muc

+0

AHHHH、私はそれをやった!私は画像でtextField.backgroundを設定し、それはうまくいった! – muc

答えて

8

ルック:。?

[searchBar setSearchFieldBackgroundImage:[UIImage imageNamed:@"search_bar"] forState:UIControlStateNormal]; 
8

=)あなたが呼び出すことができるスウィフト2とiOS 9で

for (UIView *subView in _searchBar.subviews) { 
    for(id field in subView.subviews){ 
     if ([field isKindOfClass:[UITextField class]]) { 
      UITextField *textField = (UITextField *)field; 
      [textField setBackgroundColor:[UIColor grayColor]]; 
     } 
    } 
} 
2

UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).backgroundColor = UIColor.darkGrey() 

スウィフト3:スウィフト3で

UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).backgroundColor = UIColor.darkGrey() 
+1

私のために仕事をしなかった – SunilG

+2

'searchBarStyle'が' minimal'であれば動作しません。 – enreas

+0

言及したように、解決策は次のとおりです。http://stackoverflow.com/a/42626728/2229062 – yohannes

2

ソリューション:

if let txfSearchField = searchController.searchBar.value(forKey: "_searchField") as? UITextField { 
     txfSearchField.borderStyle = .none 
     txfSearchField.backgroundColor = .lightGray 
} 
関連する問題