Like @aliamcami, all the answers before did not work as I would expect, either the answer did not work for me or it works but it needs too much “dummy” code. So I share another answer wrote in Swift 4 with simplified logic:
for textField in searchController.searchBar.subviews.first!.subviews where textField is UITextField {
textField.subviews.first?.backgroundColor = .white
textField.subviews.first?.layer.cornerRadius = 10.5 //I set 10.5 because is approximately the system value
textField.subviews.first?.layer.masksToBounds = true
//Continue changing more properties...
}
textField.subviews.first
is the “_UISearchBarSearchFieldBackgroundView” subview which add visual effects behind the UIFieldEditor
.
Edited
After some development and many bugs, I finished with this elegant solution (that I am sure Apple would not be happy to approve, but I do not know) that works from iOS 10 to iOS 12:
if let textField = searchBar.value(forKey: "searchField") as? UITextField {
textField.backgroundColor = myColor
//textField.font = myFont
//textField.textColor = myTextColor
//textField.tintColor = myTintColor
// And so on...
let backgroundView = textField.subviews.first
if #available(iOS 11.0, *) { // If `searchController` is in `navigationItem`
backgroundView?.backgroundColor = UIColor.white.withAlphaComponent(0.3) //Or any transparent color that matches with the `navigationBar color`
backgroundView?.subviews.forEach({ $0.removeFromSuperview() }) // Fixes an UI bug when searchBar appears or hides when scrolling
}
backgroundView?.layer.cornerRadius = 10.5
backgroundView?.layer.masksToBounds = true
//Continue changing more properties...
}
When the searchBar
is in the tableHeaderView
the above code can be called in viewWillAppear
, but if it is in the navigationItem
on iOS 11 and above it should be called in viewDidAppear
.