如何在Swift中更改UISearchBar上的"取消"按钮的颜色

Nic*_*k89 24 uisearchbar ios swift

我添加了一个UISearchBar到我的顶部PFQueryTableViewController.我已将searchBar的颜色更改为我的应用程序的颜色,但在执行此操作时,它似乎也将其右侧的"取消"按钮的颜色更改为相同的颜色.理想情况下,我希望颜色为白色.

此图显示了当前的外观:

它看起来没有"取消"按钮,但它有与searchBar相同的颜色(你仍然可以按它等)

有没有办法让我将这个'取消按钮的颜色改为白色?我尝试的一切似乎没有任何区别.

代码我用来制作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)
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

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

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()

        }

    }

}
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!:)

Nic*_*k89 28

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

 let cancelButtonAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
 UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes , for: .normal)
Run Code Online (Sandbox Code Playgroud)


Inc*_*Dev 12

在代码中使用此单行更改取消按钮的颜色:

UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes([NSAttributedStringKey(rawValue: NSAttributedStringKey.foregroundColor.rawValue): UIColor.white], for: .normal)
Run Code Online (Sandbox Code Playgroud)

使用Swift 4.0检查Xcode 9.2


sat*_*god 11

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

let cancelButtonAttributes: [String: AnyObject] = [NSForegroundColorAttributeName: UIColor.white]

UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes(cancelButtonAttributes, for: .normal)
Run Code Online (Sandbox Code Playgroud)

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


Dav*_*Liu 8

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


Abh*_*ain 7

斯威夫特4.2

UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.black], for: .normal)
Run Code Online (Sandbox Code Playgroud)


Ram*_*Ram 6

我知道这个问题确实有足够的答案,但这里有一个简单的方法来实现,搜索栏背景颜色和取消按钮背景颜色我们可以直接在情节提要属性检查器中更改它。

搜索栏背景颜色

在此处输入图片说明

SearchBar 取消按钮颜色

在此处输入图片说明


Mat*_*att 5

Swift 4.2 版本,基于其他答案:

let cancelButtonAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key(rawValue: NSAttributedString.Key.foregroundColor.rawValue): UIColor.orange]
UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes(cancelButtonAttributes, for: .normal)
Run Code Online (Sandbox Code Playgroud)