如何更改Swift中UISearchBar上“取消”button的颜色

我已经添加了一个UISearchBar到我的PFQueryTableViewController的顶部。 我已经改变了searchBar的颜色作为我的应用程序的颜色,但在这样做,它似乎也已经改变了“取消”button的颜色右边的相同的颜色。 理想情况下,我想要的颜色是白色的。

这张图片显示了它目前的样子:

它看起来像没有“取消”button,但是,它只是与searchBar相同的颜色(你仍然可以按下它等)

有没有办法让我改变这个“取消”button的颜色为白色? 我所尝试过的一切似乎都没有什么区别。

我用来使UISearchBar这个颜色的代码是:

 UISearchBar.appearance().barTintColor = UIColor(hue: 359/360, saturation: 67/100, brightness: 71/100, alpha: 1) UISearchBar.appearance().tintColor = UIColor(hue: 359/360, saturation: 67/100, brightness: 71/100, alpha: 1) 

在故事板中,我设置了这些:

在这里输入图像说明

最后,为了在SearchBar中创build占位符和文本白色,我使用了:

 for subView in self.filmSearchBar.subviews { for subsubView in subView.subviews { if let searchBarTextField = subsubView as? UITextField { searchBarTextField.attributedPlaceholder = NSAttributedString(string: NSLocalizedString("Search Cinevu film reviews", comment: ""), attributes: [NSForegroundColorAttributeName: UIColor.whiteColor()]) searchBarTextField.textColor = UIColor.whiteColor() } } } 

谢谢你的帮助! 🙂

环顾四周,这似乎是实现我所需要的最好的方法:

 let cancelButtonAttributes: NSDictionary = [NSForegroundColorAttributeName: UIColor.whiteColor()] UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes as? [String : AnyObject], forState: UIControlState.Normal) 

只要将UIColor.whiteColor()更改为任何你想要的颜色即可。 用Swift 2testingiOS 9

你试过UISearchBar.appearance()。tintColor = UIColor.whiteColor()

基于Nick89的代码,我改变了Swift 3.1

 let cancelButtonAttributes: [String: AnyObject] = [NSForegroundColorAttributeName: UIColor.white] UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes(cancelButtonAttributes, for: .normal) 

我只想改变UISearchBar而不是所有的UIBarButton,所以我使用像UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self])