Cannot change search bar background color

I have a search bar:

let searchBar:UISearchBar = UISearchBar(frame: CGRectMake((searchView.frame.width - UIScreen.mainScreen().bounds.width / 1.6) / 2, 0, UIScreen.mainScreen().bounds.width / 1.6, 24))

and I want to change text input part background color. For this I’ve tried:

  • iOS 11 customise search bar in navigation bar
  • UISearchDisplayDelegate how to remove this opaque view?
  • Automatically show text cursor in UISearchBar
  • “: Range {0, 10} out of bounds; string length 9” error with Undo
  • UISearchBar Scope Bar Position?
  • UISearchBar subview of UITableViewHeader?
  • searchBar.barTintColor = UIColor(red: 0/255, green: 74/255, blue: 103/255, alpha: 1)
    
    searchBar.backgroundColor = UIColor.redColor()
    

    but these both variants do not work. How can I change background color of my UISearchBar textInput part and what I did wrong?

    10 Solutions Collect From Internet About “Cannot change search bar background color”

    See Demo project : Demo

    You are adding the below code in ViewDidLoad and Change the textfield background color RED,

    for subView in searchBar.subviews
    {
        for subView1 in subView.subviews
        {
    
            if subView1.isKindOfClass(UITextField)
            {
                subView1.backgroundColor = UIColor.redColor()
            }
        }
    
    }
    

    Red Color of TextField in SearchBar.

    enter image description here

    If you only want to change it in your ViewController and don’t want anywhere else to effect then use

    for view in searchBar.subviews {
                for subview in view.subviews {
                    if subview .isKindOfClass(UITextField) {
                        let textField: UITextField = subview as! UITextField
                        textField.backgroundColor = UIColor.redColor()
                    }
                }
            }
    

    But if you want it to be change in whole app and targeting the iOS 9.0 or later then should be using appearanceWhenContainedInInstancesOfClasses like

    UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).backgroundColor = UIColor.redColor()
    

    For Swift 3+, use this:

    for subView in searchController.searchBar.subviews {
    
        for subViewOne in subView.subviews {
    
            if let textField = subViewOne as? UITextField {
    
               subViewOne.backgroundColor = UIColor.red
    
               //use the code below if you want to change the color of placeholder
               let textFieldInsideUISearchBarLabel = textField.value(forKey: "placeholderLabel") as? UILabel
                    textFieldInsideUISearchBarLabel?.textColor = UIColor.blue
            }
         }
    }
    

    Just like this

    let searchBar:UISearchBar = UISearchBar(frame: CGRectMake((searchView.frame.width - UIScreen.mainScreen().bounds.width / 1.6) / 2, 0, UIScreen.mainScreen().bounds.width / 1.6, 24))
    let searchTextField = searchBar.valueForKey("_searchField") as? UITextField
    searchTextField?.backgroundColor = UIColor.redColor()
    

    A very common answer to this question on the web is this solution described above:

    for subView in searchBar.subviews {
        for subViewInSubView in subView.subviews {   
            if subViewInSubView.isKindOfClass(UITextField) {
                subViewInSubView.backgroundColor = UIColor.purpleColor()
           }
        }
    }
    

    But it didn’t work for me using XCode 7 and iOS 9, and I noticed that around the web many others reported that it didn’t work for them, either. I discovered that the UITextField subview isn’t created (or at least it isn’t added as a subview) until it is referenced, and one way it can be referenced is by the placeholder field, e.g., one could add this line before searching the subviews for the UITextField class:

    searchBar.placeholder = searchBar.placeholder
    

    The way to do this only using Apple APIs is to create an image and use setSearchFieldBackgroundImage:

    self.searchBar.setSearchFieldBackgroundImage(UIImage(named: "SearchFieldBackground"), for: UIControlState.normal)
    

    It will even animate the corners properly if you create a rounded rect and dynamically show and hide buttons.

    Example using this image: enter image description here

    enter image description here

    Set any color you want. SWIFT 3

    public extension UISearchBar {
      public func setStyleColor(_ color: UIColor) {
        tintColor = color
        guard let tf = (value(forKey: "searchField") as? UITextField) else { return }
        tf.textColor = color
        if let glassIconView = tf.leftView as? UIImageView, let img = glassIconView.image {
          let newImg = img.blendedByColor(color)
          glassIconView.image = newImg
        }
        if let clearButton = tf.value(forKey: "clearButton") as? UIButton {
          clearButton.setImage(clearButton.imageView?.image?.withRenderingMode(.alwaysTemplate), for: .normal)
          clearButton.tintColor = color
        }
      }
    }
    
    extension UIImage {
    
      public func blendedByColor(_ color: UIColor) -> UIImage {
        let scale = UIScreen.main.scale
        if scale > 1 {
          UIGraphicsBeginImageContextWithOptions(size, false, scale)
        } else {
          UIGraphicsBeginImageContext(size)
        }
        color.setFill()
        let bounds = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        UIRectFill(bounds)
        draw(in: bounds, blendMode: .destinationIn, alpha: 1)
        let blendedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return blendedImage!
      }
    }
    

    Just try your code as below in playground. If still that won’t work, add more code to your question…

    let searchView = UIView(frame: CGRect(x: 0.0,y: 0.0, width: 100, height: 50))
    
    let searchBar:UISearchBar = UISearchBar(frame: CGRectMake((searchView.frame.width - UIScreen.mainScreen().bounds.width / 1.6) / 2, 0, UIScreen.mainScreen().bounds.width / 1.6, 24))
    
    for subView in searchBar.subviews {
        for subViewInSubView in subView.subviews {   
            if subViewInSubView.isKindOfClass(UITextField) {
                subViewInSubView.backgroundColor = UIColor.purpleColor()
            }
        }
    }
    

    I do it with this way(Swift 3+ solution):

    let textFieldInsideSearchBar = searchBar.value(forKey: "searchField") as? UITextField
    textFieldInsideSearchBar?.backgroundColor = UIColor.red
    

    FWIW I’m solving this problem by creating a computed variable named textField.

    extension UISearchBar {
        var textField: UITextField? {
            return subviews.first?.subviews.first(where: { $0.isKind(of: UITextField.self) }) as? UITextField
        }
    }