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 have made a seemingly unnecessary change to the UISearchBar
, specifically it's view hierarchy.
In further, the "text field" of a search bar is no longer accessible in the search bar's subviews, causing all of the previous solutions to "access" and change the background color of the text field, or any property of the text field for that matter.
FYI: I am specifically talking about the color behind the text... which now as of 11 defaults to white unless you specify the search bar style to be minimal.
UPDATE 1:
Since my posting of this question, I still have not found a valid or really any real solution to this issue. The closest I have seem to come is to dive deep into the appearance for instance properties
[[UISearchBar class] appearanceWhenContainedInInstancesOfClasses:(nonnull NSArray<Class<UIAppearanceContainer>> *)]
of the UISearchBar
. Playing around with the found UITextField
via methods such as the following:
if ([view isKindOfClass:[UITextField class]]) {
return (UITextField*)view;
}
UITextField *searchTextField;
for (UIView *subview in view.subviews) {
searchTextField = [self searchViewForTextFieldBg:subview];
if (searchTextField) {
break;
}
}
return searchTextField;
you can begin drawing a new background view to be placed behind the view. However, the issues I had found too tedious to pursue further were drawing the a view with the correct frame / bounds to mimic exactly the original background.
Hopefully someone can find the actual solution to this problem. Nice miss apple...
UISearchBar provides a text field for entering text, a search button, a bookmark button, and a cancel button. A search bar doesn’t actually perform any searches. You use a delegate, an object conforming to the UISearchBarDelegate protocol, to implement the actions when the user enters text or clicks buttons.
var tintColor: UIColor! The tint color to apply to key elements in the search bar. A Boolean value that indicates whether the search bar is translucent ( true) or not ( false ). A bar style that specifies the search bar’s appearance. Defines the stylistic appearance of different types of views.
You can customize the appearance of search bars one at a time, or you can use the appearance proxy ( [UISearchBar appearance]) to customize the appearance of all search bars in an app. In general, you should specify a value for the normal state to be used by other states which don’t have a custom value set.
I think you may be looking for this, right? But I've it in Swift :(
@IBOutlet weak var sbSearchBar: UISearchBar!
if let textfield = sbSearchBar.value(forKey: "searchField") as? UITextField {
textfield.textColor = UIColor.blue
textfield.backgroundColor = UIColor.yellow
}
Here is result:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With