I understand that this question has been asked many, many times on SO. However, as Apple does best, with the release of iOS 11, they seem to ha
let searchBar = UISearchBar(frame: CGRect())
let searchField: UITextField? = searchBar.value(forKey: "searchField") as? UITextField
let searchBarBackground: UIView? = searchBar.value(forKey: "background") as? UIView
// searchBarBackground?.removeFromSuperview()
if searchField != nil {
var frame = searchField?.frame
frame?.size.height = 30
searchField?.frame = frame!
searchField?.backgroundColor = .yellow
}
searchBar.barTintColor = .red
searchBar.delegate = self
searchBar.backgroundColor = .green
If we set background colors for UISearchBar with code above, we'll see the colored subviews as follow images(click links to see). 
backgroundColor
for Superview of UISearchBar subviewsWe can see the Class Name of green view is UISearchBar in Object inspector.
So, if we use searchBar.backgroundColor = .green
, we'll set the backgroundColor of Superview green. Therefore, the UISearchBar instance property backgroundColor
will set the superview's background color.
Superview of UISearchBar
barTintColor
for UISearchBarBackgroundWe can see the Class Name of red view is UISearchBarBackground in Object inspector.
However, there's no direct method to access the view, we can use KVC searchBar.value(forKey: "background") as? UIView
try to get searchBarBackground.
If we use searchBar.barTintColor = .red
, we'll set the backgroundColor of UISearchBarBackground's view red. In order to remove two black border on the tint bar layer, we have to remove the background from superview.
barTintColor of UISearchBar
searchField?.backgroundColor
for UITextFieldWe can see the Class Name of yellow view is _UISearchBarSearchFieldBackgroundView (Subview of UISearchBarTextField) in Object inspector.
There's no direct method to access the searchField, same as searchBarBackground. We can also use KVC searchField: UITextField? = searchBar.value(forKey: "searchField") as? UITextField
try to get searchField.
If we use searchField?.backgroundColor = .yellow
, we'll set the backgroundColor of UITextField yellow. Therefore, if we want to set text field background color, we have to access the searchField with KVC first
UITextField of UISearchBar