web-dev-qa-db-fra.com

UISearchBar: effacer la couleur d'arrière-plan ou définir l'image d'arrière-plan

Comment définir l'image d'arrière-plan ou effacer l'arrière-plan d'une barre de recherche, comme l'application de note?

41
Momi

Je viens de trouver une solution qui fonctionne vraiment bien. Vous devez remplacer l'UISearchBar, puis masquer les couches d'arrière-plan et de contrôle de segment. Dessinez ensuite l'arrière-plan.

@ .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

J'espère que cela t'aides!

8
Designerd

Une manière pérenne:

[searchBar setBackgroundImage:[UIImage new]];
[searchBar setTranslucent:YES];
175
Rudolf Adamkovič

mj_ ​​a la réponse que j'ai utilisée. j'allais juste commenter comme tel mais je ne peux pas encore. Je vais donc simplement poster ma propre réponse avec mon implémentation où j'ajoute une barre de recherche en haut d'une vue de table avec un BG semi-transparent.

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

J'ai eu des problèmes avec la réponse ci-dessus. J'ai utilisé ce qui suit.

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

Cela a fonctionné pour moi (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;
        }
    }   
}
12
Chris

Vous avez ici deux questions:
1.UISearchBar couleur d'arrière-plan claire:
Voir ma réponse ici

2. Définir l'image d'arrière-plan Solution: ( Si vous êtes dans iOS 5.0 + )

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

REMARQUE: vous pouvez également essayer d'utiliser une image transparente comme arrière-plan.

J'espère que cela t'aides.

8
thesummersign

Je préfère simplement mettre l'alpha à 0 afin que vous puissiez masquer/afficher à la demande.

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

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

searchBar.searchBarStyle = UISearchBarStyleMinimal;

4
Brad Thomas

Comment définir la couleur d'arrière-plan dans UISearchBar:

#import <QuartzCore/QuartzCore.h>

Ensuite, établissez une connexion de sortie à la barre de recherche (disons, objSearchbar), et utilisez ces lignes:

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

self.tweetSearchbar.layer.backgroundColor = [UIColor blueColor].CGColor;
4
iGautam
2
hennes

avec iOS8 sdks Apple déplacé @ "UISearchBarBackground" voir un niveau plus en profondeur, donc il faudra regarder les sous-vues des vues enfant comme ci-dessous,

for (UIView *subview in searchBar.subviews) {
        for(UIView* grandSonView in subview.subviews){
            if ([grandSonView isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
                grandSonView.alpha = 0.0f;
            }else if([grandSonView isKindOfClass:NSClassFromString(@"UISearchBarTextField")] ){
                NSLog(@"Keep textfiedld bkg color");
            }else{
                grandSonView.alpha = 0.0f;
            }
        }//for cacheViews
    }//subviews
2
Xmobile Vietnam

Définir l'image d'arrière-plan

    UIImageView *backgroundView = [[UIImageView alloc] initWithFrame:searchBar.bounds];
    backgroundView.image = [UIImage imageNamed:@"xxxx.png"];
    [searchBar insertSubview:backgroundView atIndex:1]; // at index 1 but not 0
    [backgroundView release];
1
iwill

Bon mot:

[[self.theSearchBar.subviews objectAtIndex:0] removeFromSuperview];
0
fuzz