更改UISearchBar textColor无法正常工作

Ran*_*jit 3 google-maps uisearchbar google-places-api uiappearance

我正在使用google places API for autoComplete小部件.我正在使用swift在ios 9+中显示全屏控制.我正在添加文档中给出的完整控件.

我添加了文档中显示的代码.现在我想将searchBar文本颜色更改为whiteColor.

所以我尝试了这个

UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).textColor = UIColor.whiteColor()
Run Code Online (Sandbox Code Playgroud)

但我没有得到理想的行为.以下是截图

**在此处输入图片说明**

这已在Docs中给出

https://developers.google.com/places/ios-api/autocomplete#use_a_table_data_source

但这不起作用.对此我需要帮助.

Nit*_*hel 8

你需要创建一个像follwoing这样的扩展:

public extension UISearchBar {

    public func setNewcolor(color: UIColor) {
        let clrChange = subviews.flatMap { $0.subviews }
        guard let sc = (clrChange.filter { $0 is UITextField }).first as? UITextField else { return }
        sc.textColor = color
    }
}
Run Code Online (Sandbox Code Playgroud)

并使用以下代码更改颜色:

 controller.searchBar.setNewcolor(UIColor.redColor())
Run Code Online (Sandbox Code Playgroud)

输出是:

在此输入图像描述

更新:

对于searchBar文本的更改颜色,GMSAutocompleteViewController您需要执行以下代码:

let searchBarTextAttributes: [String : AnyObject] = [NSForegroundColorAttributeName: UIColor.redColor(), NSFontAttributeName: UIFont.systemFontOfSize(UIFont.systemFontSize())]
UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).defaultTextAttributes = searchBarTextAttributes
Run Code Online (Sandbox Code Playgroud)

这改变了文字如下图所示:

在此输入图像描述

如果你想改变占位符文本和它的颜色searchBar.您需要执行以下代码:

let placeholderAttributes: [String : AnyObject] = [NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: UIFont.systemFontOfSize(UIFont.systemFontSize())]

let attributedPlaceholder: NSAttributedString = NSAttributedString(string: "Find a place", attributes: placeholderAttributes)
UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).attributedPlaceholder = attributedPlaceholder
Run Code Online (Sandbox Code Playgroud)

它将显示如下:

在此输入图像描述


Sho*_*wan 6

使用Swift 3 的波纹管代码

if #available(iOS 9.0, *) {
  UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSForegroundColorAttributeName: UIColor.green]
  } else {
  // Fallback on earlier versions
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。