google-mapsuisearchbargoogle-places-apiuiappearance

Change UISearchBar textColor not working


I am using google places API for autoComplete widget. I am showing the full screen control in ios 9+ using swift. I am adding a full control as given in the docs.

I have added the code as shown in the docs. Now I want to change the searchBar text color to whiteColor.

So I tried this

UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).textColor = UIColor.whiteColor()

But I am not getting the desired behaviour. Below is the screenshot

**enter image description here**

This has been given in Docs

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

But this is not working. I need help with regarding to this.


Solution

  • You need to create an extension like 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
        }
    }
    

    And change color using following code:

     controller.searchBar.setNewcolor(UIColor.redColor())
    

    Output is :

    enter image description here

    Update:

    For the change color of searchBar text for the GMSAutocompleteViewController you need to do following code:

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

    That change the text out put like following image:

    enter image description here

    And if you wish to change placeholder text and it's color for searchBar. You need to do following code:

    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
    

    It will be show like:

    enter image description here