Ray Saudlach
Ray Saudlach

Reputation: 660

UISearchBar Properties

I am working on a legacy application and can't figure out why a UISearchBar is not showing up correctly.

I am trying to make the background be white or any other color but can't seem to set it correctly. How can I set the background so it's not dark as shown below?

Here is what I have tried:

[self.searchController.searchBar setSearchBayStyle:UISearchBarStyleDefault];
[self.searchController.searchBar setBackgroundImage:[UIImage imageWithCGImage:(__bridge CFImageRef) ([UIColor whiteColor])]];

The search bar is added in programmatically so I can't use the attributes inspector.

Alternatively, is there a way to print what the search bar properties are for style, etc via NSLog?

UISearchBar

Upvotes: 1

Views: 139

Answers (2)

Rakshith Nandish
Rakshith Nandish

Reputation: 649

I have created an extension for UISearchBar customisation Link: https://github.com/Rakshith-Nandish/SearchBarCustomiser

Also to change the UITextField background color you can use this

 let textFieldSearchBar = self.value(forKey: "searchField") as? UITextField
    textFieldSearchBar?.backgroundColor = <your desired color value>

Upvotes: 0

Shamim Hossain
Shamim Hossain

Reputation: 1760

Every search bar view contains a textfield and here you see background color of this textfield. By default it uses tintColor.

To set manually you need to create a method for recursively finding up textfield and then background color on it.

- (UITextField*)searchSubviewsForTextFieldIn:(UIView*)view
{
    if ([view isKindOfClass:[UITextField class]]) {
        return (UITextField*)view;
    }
    UITextField *searchedTextField;
    for (UIView *subview in view.subviews) {
        searchedTextField = [self searchSubviewsForTextFieldIn:subview];
        if (searchedTextField) {
            break;
        }
    }
    return searchedTextField;
}

And then call this method as:

 [[self searchSubviewsForTextFieldIn:self.searchController.searchBar] setBackgroundColor:[UIColor whiteColor]];

Hope it will work!

Upvotes: 1

Related Questions