Search code examples
iosobjective-cswiftuisearchbarios11

iOS 11 UISearchBar background color


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.

  • Does anyone know how to actually adjust the background color of a search bar in iOS 11?

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...


Solution

  • 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:

    enter image description here