UISearchBar:清除背景颜色或设置背景图片。

41
如何设置搜索栏的背景图片或清除背景,例如笔记应用程序?
如何在搜索栏中设置背景图片或者清除背景呢?例如,像笔记应用程序一样。

self.searchBar.setSearchFieldBackgroundImage(UIImage(), for: .normal) 自我.searchBar.setSearchFieldBackgroundImage(UIImage(), for: .normal) - AndrewK
13个回答

175

一种具有未来性的方法:

[searchBar setBackgroundImage:[UIImage new]];
[searchBar setTranslucent:YES];

1
可以在iOS 5和iOS 6上运行。已在iPad上测试过。 - AvtarSingh Suchariya
1
如果您使用ARC,那么它就可以为您发布。 - Kevlar
1
这也应该是答案,我个人认为! - Kevlar
8
马丁,不要用 MRC 啊。除非你需要超高性能的代码,即使如此,我也不确定在大多数情况下使用 ARC 不会更好。 - powerj1984
4
确认这适用于iOS 7。 - RyanG
显示剩余9条评论

29

mj_提供了我所使用的答案。本来我只是想评论一下,但我还不能这样做。因此,我将发布自己的答案,并在其中添加一个带有半透明背景的搜索栏到表视图的顶部。

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;
    }
}   

3
感谢您在2011年的准确性仍然受到认可。我正在寻找您示例中的最后五行。干杯! - epologee
如果您使用一个UIImageView来显示背景图像,并且想要将搜索栏隐藏在导航栏后面,则图像的高度需要为44像素。或者使用clipsToBounds = YES,否则会在导航栏下方绘制一条1像素的线。 - Olof
我是这样做的:NSClassFromString([NSString stringWithFormat:@"U%@Sea%@", @"I", @"rchBarBackground"]),以防万一苹果搜索命名为私有类的字符串..但不知道是否有帮助(?) - hfossli
1
苹果会因为使用私有类“UISearchBarBackground”而拒绝此代码吗? - nonamelive
我在一个提交到应用商店的应用程序中使用了这个,而且没有被拒绝。 - katbyte

14

我对上面的答案有问题。我使用了以下方法。

for (UIView *subview in searchBar.subviews) {
    if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
        [subview removeFromSuperview];
        break;
    }
}

自SDK 4.2版本开始,这会破坏按钮和字段。 - Simon Woodside
我错了,只有在将这段代码放入layoutSubviews中才会这样做。傻瓜。 - Simon Woodside
3
不要忘记在 for 循环后设置你的颜色 - [searchBar setBackgroundColor:[UIColor clearColor]]; - beryllium
这种方法在iOS 5.1上的Xcode 4.4.1中不起作用。 - Maksim

12

这对我有用(适用于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;
        }
    }   
}

8
我刚刚想到了一个非常好的解决方案。您需要覆盖UISearchBar,然后隐藏背景和段控制层。然后绘制背景。
@ .m
#import "UISearchBar.h" 
#import <QuartzCore/QuartzCore.h>

@implementation UISearchBar(CustomBackground)

- (id)init
    {
        for ( UIView * subview in self.subviews ) 
        {
            if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground") ] ) 
                subview.alpha = 0.0;  

            if ([subview isKindOfClass:NSClassFromString(@"UISegmentedControl") ] )
                subview.alpha = 0.0; 
        } 

        return self;
    }

+ (UIImage *) bgImagePortrait
    {
        static UIImage *image = nil;
        if (image == nil)
            image = [[UIImage imageNamed:@"UISearchBarBack.png"] retain ];

        return image;
    }

+ (UIImage *) bgImageLandscape
    {
        static UIImage *image = nil;
        if (image == nil)
            image = [[UIImage imageNamed:@"UISearchBarBack.png"] retain];

        return image;
    }

- (void) drawLayer:(CALayer *)layer inContext:(CGContextRef)contenxt
    {
        if ([self isMemberOfClass:[UISearchBar class]] == NO)
            return; 

        UIImage * image = ( self.frame.size.width > 320 ) ? [UISearchBar bgImageLandscape ] : [UISearchBar bgImagePortrait ];  

        for ( UIView * subview in self.subviews ) {
            if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground") ] ) 
                subview.alpha = 0.0; 

            if ([subview isKindOfClass:NSClassFromString(@"UISegmentedControl") ] )
                subview.alpha = 0.0; 
        }

        CGContextTranslateCTM( contenxt , 0 , image.size.height );
        CGContextScaleCTM( contenxt, 1.0, -1.0 );
        CGContextDrawImage( contenxt , CGRectMake( 0 , 0 , image.size.width , image.size.height ), image.CGImage );
    }  

@end

@ .h

#import <Foundation/Foundation.h>
#import <QuartzCore/QuartzCore.h>


@interface UISearchBar(CustomBackground) 

@end

希望这能帮到你!

1
对我没用...(iOS 4.2) - Chris
2
在iOS 5上对我也不起作用。 - jjxtra

8

你有两个问题:
1.UISearchBar清除背景颜色:
请查看我的答案

2.设置背景图片的解决方案:(如果你使用的是iOS 5.0 +)

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

注意:您还可以尝试使用透明图像作为背景。

希望这能帮到您。


4

我建议将alpha值设置为0,这样您可以根据需要隐藏/显示。

// Hide
[[self.theSearchBar.subviews objectAtIndex:0] setAlpha:0.0];

// Show
[[self.theSearchBar.subviews objectAtIndex:0] setAlpha:1.0];

这在Xcode 4.4.1中不起作用。 - Maksim

4
如何在 UISearchBar 中设置背景颜色:
#import <QuartzCore/QuartzCore.h>

然后将一个出口连接到搜索栏(比如说,objSearchbar),并使用以下代码:

for (UIView *subview in self.objSearchbar.subviews) 
{
    if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) 
    {
        [subview removeFromSuperview];
        break;
    }
}

self.tweetSearchbar.layer.backgroundColor = [UIColor blueColor].CGColor;

这个东西对我来说运行良好。+1 评分。 - Nirav Jain

4

searchBar.searchBarStyle = UISearchBarStyleMinimal;

翻译为:搜索栏样式设置为最小化。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接