2011-08-29 74 views
7

我試圖改變UISearchBar的輸入字段的背景顏色。它是您輸入要搜索的文本的圓角視圖,默認顏色是白色。我想將它更改爲灰色UISearchBar:改變輸入字段的背景顏色

我想:

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

但它不工作:(

我也試圖插入的圖像以文本字段,但它似乎圓形圖從文本字段分開所以,任何線索

+0

ü應該在代碼中創建搜索欄而不是在interfacebuilder.i中創建IB.so時出現同樣的問題se代碼創建搜索欄 –

+0

感謝您的回覆。我會試試 – muc

+0

AHHHH,我做到了!我設置textField.background與圖像,它的工作,耶! – muc

回答

8

看功能:?

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

=)

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

在夫特2和iOS 9可以調用:

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

夫特3:

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

Did not for me – SunilG

+2

如果'searchBarStyle'爲'minimal',它將不起作用。 – enreas

+0

作爲@enreas提到,解決方案是:http://stackoverflow.com/a/42626728/2229062 – yohannes

2

解在夫特3:

if let txfSearchField = searchController.searchBar.value(forKey: "_searchField") as? UITextField { 
     txfSearchField.borderStyle = .none 
     txfSearchField.backgroundColor = .lightGray 
}