Skip to content

Instantly share code, notes, and snippets.

@wavecos
Last active November 19, 2021 00:09
Show Gist options
  • Save wavecos/970a0e0bad82d258c22c to your computer and use it in GitHub Desktop.
Save wavecos/970a0e0bad82d258c22c to your computer and use it in GitHub Desktop.
Customize Color, background from UISearchBar in Swift

Customize Color, background from UISearchBar in Swift

// as UISearchBar extension
extension UISearchBar {
  func changeSearchBarColor(color : UIColor) {
    for subView in self.subviews {
      for subSubView in subView.subviews {
        if subSubView.conformsToProtocol(UITextInputTraits.self) {
          let textField = subSubView as UITextField
          textField.backgroundColor = color
          break
        }
      }
    }
  }
}
@hechukwu
Copy link

hechukwu commented Jan 7, 2020

@hell4opt Yeah I did for the size I had to do this let size = CGSize(width: self.frame.size.width, height: 45) you have to play with the height till you get what you want.

@hechukwu
Copy link

hechukwu commented Jan 7, 2020

This is my full code for anyone having the same issue
extension UISearchBar {
  func changeSearchBarColor(color: UIColor, size: CGSize) {
        UIGraphicsBeginImageContext(self.frame.size)
        color.setFill()
        UIBezierPath(rect: self.frame).fill()
        let bgImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        self.setSearchFieldBackgroundImage(bgImage, for: .normal)
    }
}

Then you call it like so yourSearchBar.changeSearchBarColor(color: yellow, size: CGSize(width: yourSearchBar.frame.size.width, height: 45))

@dimabiserov
Copy link

This is my full code for anyone having the same issue
extension UISearchBar {
  func changeSearchBarColor(color: UIColor, size: CGSize) {
        UIGraphicsBeginImageContext(self.frame.size)
        color.setFill()
        UIBezierPath(rect: self.frame).fill()
        let bgImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        self.setSearchFieldBackgroundImage(bgImage, for: .normal)
    }
}

Then you call it like so yourSearchBar.changeSearchBarColor(color: yellow, size: CGSize(width: yourSearchBar.frame.size.width, height: 45))

thanks!) but the height does not work (and the corner radius is not enough)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment