SearchBar,如何更改文字颜色?

这是我的搜索栏的样子

我的search栏有默认的灰色文本,但我希望它是白色文本。 我无法弄清楚如何使用swift来改变范围栏的文本颜色,而你无法从故事板上做到这一点。 我发现的最接近的是

searchBarOutlet.setScopeBarButtonTitleTextAttributes([NSForegroundColorAttributeName: UIColor.whiteColor()], forState:UIControlState.Normal) 

但唉这也不行。 有任何想法吗?

它有点难以访问UISearchbar内的Textfield。

这是如何工作的:

 for subView in self.searchBarOutlet.subviews { for secondLevelSubview in subView.subviews { if (secondLevelSubview.isKindOfClass(UITextField)) { if let searchBarTextField:UITextField = secondLevelSubview as? UITextField { //set the color here like this: searchBarTextField.textColor = UIColor.redColor() break; } } } } 

较短的解决scheme:

 var textFieldInsideSearchBar = yourSearchbar.valueForKey(“searchField”) as? UITextField textFieldInsideSearchBar?.textColor = yourcolor 
 // My preferred way of accessing searchField if let searchTextField = self.searchBar.valueForKey("searchField") as? UITextField { searchTextField.textAlignment = NSTextAlignment.Left } 

Swift 3

 UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).textColor = UIColor.white 

在我的情况下,迅速3.0

(mySearchBar.value(forKey:“searchField”)为?UITextField)?textColor = UIColor.white