UISearchBar: clear background color or set backgro

2020-01-27 11:32发布

How can set the background image, or clear the background, of a search bar, like the note application?

13条回答
霸刀☆藐视天下
2楼-- · 2020-01-27 12:24

mj_ has the answer that i used. i was just going to comment as such but i can't yet. So i'll just post my own answer with my implementation where I add a search bar to the top of a table view with a semi-transparent BG.

DLog(@"    Add search bar to table view"); 

//could be a UIImageView to display an image..?
bg = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 45)] autorelease];
bg.backgroundColor        = [UIColor blackColor];
UISearchBar *sb           = [[[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, 290, 45)] autorelease];
sb.barStyle               = UIBarStyleBlackTranslucent;
sb.showsCancelButton      = NO;
sb.autocorrectionType     = UITextAutocorrectionTypeNo;
sb.autocapitalizationType = UITextAutocapitalizationTypeNone;
sb.delegate               = self;
[bg addSubview:sb];
table.tableHeaderView     = bg;

for (UIView *subview in sb.subviews) {
    if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
        [subview removeFromSuperview];
        break;
    }
}   
查看更多
Bombasti
3楼-- · 2020-01-27 12:24

searchBar.searchBarStyle = UISearchBarStyleMinimal;

查看更多
一纸荒年 Trace。
4楼-- · 2020-01-27 12:25

This worked for me (ios4.2+)

// Change the search bar background
-(void)viewWillAppear:(BOOL)animated {
    for (UIView *subview in self.searchBar.subviews) {
        if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
            UIView *bg = [[UIView alloc] initWithFrame:subview.frame];
            bg.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"search_bar_bg"]];
            [self.searchBar insertSubview:bg aboveSubview:subview];
            [subview removeFromSuperview];
            break;
        }
    }   
}
查看更多
男人必须洒脱
5楼-- · 2020-01-27 12:26

You have two questions here:
1.UISearchBar clear background color:
See my answer here

2.Set background image Solution:(If you are in iOS 5.0 +)

[[UISearchBar appearance]setSearchFieldBackgroundImage:[navBarGradImage resizableImageWithCapInsets:inset2] forState:UIControlStateNormal];

NOTE: You can also try using a transparent image as a background.

Hope this helps.

查看更多
一夜七次
6楼-- · 2020-01-27 12:28

A future-proof way:

[searchBar setBackgroundImage:[UIImage new]];
[searchBar setTranslucent:YES];
查看更多
倾城 Initia
7楼-- · 2020-01-27 12:33

I had problems w/ the answer above. I used the following.

for (UIView *subview in searchBar.subviews) {
    if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
        [subview removeFromSuperview];
        break;
    }
}
查看更多
登录 后发表回答