Can background or borders be removed from UISearch

2019-04-09 00:29发布

问题:

I'd like to get something like this:

But I was not able to remove original background (I'm using iOS5). However, it seems Apple did it:

How can I create what I want? Or, there is no choice and the only alternative I have is customize a UITextField?

Thanks for suggestions and ideas!

EDIT: After first reply, this is what I got:

Does anyone how can I remove white inner background without making all component semitransparent changing its alpha value? BTW, can I change white color by black color?

回答1:

Try this code,It worked for me

for (id img in yourSearchBar.subviews) {
        if ([img isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
           [img removeFromSuperview];    
        }
    }

In the above code yourSearchBar is the searchbar from which you want to remove the background, And the for loop is searching for the background image of UISearchBar



回答2:

You should really use the appearance protocol. You can either change it for a single instance of the UISearchBar,

UIImage *searchBg = [UIImage imageNamed:@"search_bar.png"];
[searchBar setBackgroundImage:searchBg];

or if you have multiple search bars across different scenes this will theme every instance (but call it somewhere sensible like the AppDelegate to ensure the bars are all setup correctly before you see any of them.

UIImage *searchBg = [UIImage imageNamed:@"search_bar.png"];
[[UISearchBar appearance] setBackgroundImage:searchBg];

Update: OK, to change the background of a search bar you should use one of the following,

Single instance of searchBar:

[searchBar setSearchFieldBackgroundImage:searchBg forState:UIControlStateNormal];

All instances of UISearchBars:

[[UISearchBar appearance] setSearchFieldBackgroundImage:searchBg forState:UIControlStateNormal];

Hope this helps.



回答3:

In iOS 7 you can just set:

searchBar.barTintColor = [UIColor clearColor];