开发者

SearchBar in UINavigationItem

开发者 https://www.devze.com 2023-03-26 15:43 出处:网络
I added a search bar in the UINavigationItem using the following code: UISearchB开发者_JS百科ar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectZero];

I added a search bar in the UINavigationItem using the following code:

UISearchB开发者_JS百科ar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectZero];
[searchBar sizeToFit];
searchBar.delegate = self;
self.navigationItem.titleView = searchBar;
self.navigationItem.title = self.category.title;
[searchBar release];

but the result UI is like this:

SearchBar in UINavigationItem

How can I change the color of the search bar and make it the same with the background of the navigation bar?

Thanks.


For a UINavigationBar there is multiple ways to manipulate background color of it:

  1. Set a tintColor property to a color that you need.
  2. Follow proposed way of modification to apply custom gradient or other pattern image — http://leonov.co/2011/04/uinavigationbar-and-uitoolbar-customization-ultimate-solution/

For a search bar tintColor is also available. But in your case I suggest to inherit form UISearchBar and provide implementation as shown below to get rid from background drawing routine totally. In this case you will get search bar on an transparent toolbar and will and you will need to manage only UINavigationBar color.

//TransparentSearchBar.m

@interface TransparentSearchBar()
- (void)removeBackgroundView;
@end

@implementation TransparentSearchBar

- (id)init
{
    self = [super init];

    if(self) {
        [self removeBackgroundView];
    }

    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder 
{
    self = [super initWithCoder:aDecoder];

    if(self) {
        [self removeBackgroundView];
    }

    return self;
}

- (id)initWithFrame:(CGRect)frame 
{
    self = [super initWithFrame:frame];

    if(self) {
        [self removeBackgroundView];
    }

    return self;
}

- (void)removeBackgroundView 
{
    for (UIView *view in self.subviews)
    {
        if ([view isKindOfClass:NSClassFromString
             (@"UISearchBarBackground")])
        {
            [view removeFromSuperview];
            break;
        }
    }
}

@end


If you see the documentation on UISearchBar it has the property "tintColor". Set that to color of the navigation bar.

If you do not know the color of navigationbar, get the tintColor of navigationBar.

You might also want to lay with the "translucent" property of the searchbar. Might work better.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号