2012-01-18 17 views
7

Sto provando a impostare a livello di codice l'immagine di sfondo per una barra delle linguette nella mia app. Il mio codice è il seguente:Impostazione di un'immagine di sfondo per una barra delle schede

RootViewController.h

IBOutlet UITabBar *mainTabBar; 
    IBOutlet UITabBarItem *settingsBarItem; 
    IBOutlet UITabBarItem *infoBarItem; 
    IBOutlet UITabBarItem *aboutBarItem; 

RootViewController.m

-(void)viewDidLoad { 

    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"smallMenuBackground.png"]];  
    [mainTabBar insertSubview:imageView atIndex:0]; 
    [imageView release]; 

    [super viewDidLoad]; 
} 

Questo non funziona per me.

UPDATE

AGGIORNAMENTO 23 gennaio 2012

Ok, ho fatto un po 'di progresso. Questo ha smesso di funzionare da quando ho aggiornato a Xcode 4.2 e IOS5. Sono riuscito a recuperarlo usando le opzioni di Interface Builder, ma ora funziona solo con IOS5. Idealmente avrei voluto lavorare in modo programmatico, ma per ora mi accontenterò della soluzione IB.

Non riesco proprio a farlo funzionare per le versioni precedenti.

NOTA: il mio TabBar è solo sul mio RootViewController, che è la schermata principale della mia app.

Idealmente, se ho potuto ottenere il codice di lavoro che Nithin suggerito, che sarebbe grande:

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tabBG.png"]]; 

if ([[[UIDevice currentDevice] systemVersion] floatValue] > 4.9) { 
    //iOS 5 
    [self.tabBarController.tabBar insertSubview:imageView atIndex:1]; 
} 
else { 
    //iOS 4.whatever and below 
    [self.tabBarController.tabBar insertSubview:imageView atIndex:0]; 
} 

[imageView release]; 

Qualsiasi aiuto sarebbe apprezzato.

saluti, Stephen

+1

controllare questo link. Qui però è richiesto il colore di sfondo, ma c'è un codice per mettere l'immagine come sfondo in un post. [Controllalo] (http://stackoverflow.com/questions/571028/changing-tint-background-color-of-uitabbar). – Sarah

risposta

14

È possibile utilizzare classe personalizzata per UITabBarController & ignorare la tabBarController. Qui puoi impostare i tuoi pulsanti richiesti & le loro azioni con l'immagine.

Questo è come la vostra abitudine scheda barra di classe controller può essere assomigliare:

// CustomTabBarController.h

#import <UIKit/UIKit.h> 

@interface CustomTabBarController : UITabBarController { 
    UIButton *settingsButton; 
    UIButton *infoButton; 
    UIButton *aboutUsButton; 
} 

@property (nonatomic, retain) UIButton *settingsButton; 
@property (nonatomic, retain) UIButton *infoButton; 
@property (nonatomic, retain) UIButton *aboutUsButton; 

-(void) addCustomElements; 
-(void) selectTab:(int)tabID; 

@end 

// CustomTabBarController.m

#import "CustomTabBarController.h" 

@implementation CustomTabBarController 

@synthesize settingsButton, infoButton, aboutUsButton; 

- (void)viewDidAppear:(BOOL)animated { 
    [super viewDidAppear:animated]; 


} 
-(void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    [self addCustomElements]; 
} 

-(void)addCustomElements 
{ 
    // Background 
    UIImageView* bgView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tabBarBackground.png"]] autorelease]; 
    bgView.frame = CGRectMake(0, 420, 320, 60); 
    [self.view addSubview:bgView]; 

    // Initialise our two images 
    UIImage *btnImage = [UIImage imageNamed:@"settings.png"]; 
    UIImage *btnImageSelected = [UIImage imageNamed:@"settingsSelected.png"]; 

    self.settingsButton = [UIButton buttonWithType:UIButtonTypeCustom]; //Setup the button 
    settingsButton.frame = CGRectMake(10, 426, 100, 54); // Set the frame (size and position) of the button) 
    [settingsButton setBackgroundImage:btnImage forState:UIControlStateNormal]; // Set the image for the normal state of the button 
    [settingsButton setBackgroundImage:btnImageSelected forState:UIControlStateHighlighted]; // Set the image for the selected state of the button 
    [settingsButton setBackgroundImage:btnImageSelected forState:UIControlStateSelected]; // Set the image for the selected state of the button 
    [settingsButton setBackgroundImage:btnImageSelected forState:UIControlStateDisabled]; 
    [settingsButton setImage:btnImageSelected forState:(UIControlStateHighlighted|UIControlStateSelected)]; 
    [settingsButton setTag:101]; // Assign the button a "tag" so when our "click" event is called we know which button was pressed. 
    [settingsButton setSelected:true]; // Set this button as selected (we will select the others to false as we only want Tab 1 to be selected initially 

    // Now we repeat the process for the other buttons 
    btnImage = [UIImage imageNamed:@"info.png"]; 
    btnImageSelected = [UIImage imageNamed:@"infoSelected.png"]; 
    self.infoButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
    infoButton.frame = CGRectMake(110, 426, 100, 54); 
    [infoButton setBackgroundImage:btnImage forState:UIControlStateNormal]; 
    [infoButton setBackgroundImage:btnImageSelected forState:UIControlStateSelected]; 
    [infoButton setBackgroundImage:btnImageSelected forState:UIControlStateHighlighted]; 
    [infoButton setImage:btnImageSelected forState:(UIControlStateHighlighted|UIControlStateSelected)]; 

    [infoButton setTag:102]; 

    btnImage = [UIImage imageNamed:@"aboutUs.png"]; 
    btnImageSelected = [UIImage imageNamed:@"aboutUsSelected.png"]; 
    self.aboutUsButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
    aboutUsButton.frame = CGRectMake(210, 426, 100, 54); 
    [aboutUsButton setBackgroundImage:btnImage forState:UIControlStateNormal]; 
    [aboutUsButton setBackgroundImage:btnImageSelected forState:UIControlStateSelected]; 
    [aboutUsButton setBackgroundImage:btnImageSelected forState:UIControlStateHighlighted]; 
    [aboutUsButton setImage:btnImageSelected forState:(UIControlStateHighlighted|UIControlStateSelected)]; 

    [aboutUsButton setTag:103]; 

    // Add my new buttons to the view 
    [self.view addSubview:settingsButton]; 
    [self.view addSubview:infoButton]; 
    [self.view addSubview:aboutUsButton]; 

    // Setup event handlers so that the buttonClicked method will respond to the touch up inside event. 
    [settingsButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside]; 
    [infoButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside]; 
    [aboutUsButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside]; 
} 

- (void)buttonClicked:(id)sender 
{ 
    int tagNum = [sender tag]; 
    [self selectTab:tagNum]; 
} 

- (void)selectTab:(int)tabID 
{ 
    switch(tabID) 
    { 
     case 101: 
      [settingsButton setSelected:true]; 
      [infoButton setSelected:false]; 
      [aboutUsButton setSelected:false]; 
      break; 
     case 102: 
      [settingsButton setSelected:false]; 
      [infoButton setSelected:true]; 
      [aboutUsButton setSelected:false]; 
      break; 
     case 103: 
      [settingsButton setSelected:false]; 
      [infoButton setSelected:false]; 
      [aboutUsButton setSelected:true]; 
      break; 
    } 
    self.selectedIndex = tabID; 
} 

- (void)dealloc { 
    [settingsButton release]; 
    [infoButton release]; 
    [aboutUsButton release]; 

    [super dealloc]; 
} 

@end 

Spero che questo vi aiuterà molto.

+0

Grazie Erfan, voglio solo la tabbar nel mio RootViewController, come posso chiamare la classe personalizzata? – Stephen

+0

In tal caso, puoi chiamare la classe personalizzata come menzionato sopra .....solo un po 'diverso, aggiungi un UIViewController nella tua storyboard/finestra principale. Nella classe di delega dell'app, all'interno di applicationDidFinishLaunching aggiungi viewController come sottomenu nella finestra. Quindi il tuo RootViewController apparirà nella schermata che si trova all'interno di viewController. Quindi puoi nascondere o nascondere il tuo controller di tabbar come richiesto sopra il tuo viewController. Questo è solo un suggerimento. Puoi provarlo. Spero che sarà fatto. :) – Erfan

+0

'self.selectedIndex = tabID;' questa riga deve essere modificata in 'self.selectedIndex = tabID - 101;' –

0

avere una visione personalizzata e aggiungere su UITaB bar. ora aggiungi il pulsante su quella vista e fornisci il collegamento del metodo ai pulsanti della barra delle schede. Ora puoi fare qualsiasi cosa su quella vista aggiungendo immagini o qualsiasi cosa. Funziona come barra delle schede personalizzate.

3

È necessario codificarlo condizionatamente dalla versione del sistema operativo.

Se si supporta solo iOS 5, è possibile utilizzare semplicemente la proprietà backgroundImage della barra delle linguette. Se devi supportare le versioni di iOS inferiori a 5, devi aggiungere un codice condizionale che "hacker" sul posto. Ci sono diversi approcci per farlo, eccone uno:

Custom tab bar background image - in iOS 4.x

6
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tabBG.png"]]; 

if ([[[UIDevice currentDevice] systemVersion] floatValue] > 4.9) { 
    //iOS 5 
    [self.tabBarController.tabBar insertSubview:imageView atIndex:1]; 
} 
else { 
    //iOS 4.whatever and below 
    [self.tabBarController.tabBar insertSubview:imageView atIndex:0]; 
} 

[imageView release]; 
+0

Grazie Nithin, l'ho appena provato ma non ha funzionato. – Stephen

+0

@Stephen http://www.tumblr.com/tagged/uitabbar Controlla il metodo fornito in questo link – nithin

+0

Grazie ancora Nithin, ho provato gli esempi nel link ma non sono riuscito a farlo funzionare. – Stephen

0

Quello che ho fatto in passato è creare il mio TabbarController per caricare diversi UIViewControllers. Con questo controller posso manipolare l'aspetto degli elementi tabbar e tabbar al suo interno.

Questo funziona bene per me, ma inizialmente è un po 'di lavoro. Perché devi "simulare" la UITabBarController, dal momento che in realtà non utilizza l' 'nativo' UITabBar

0
jUst call these two methods 
    hideTabBar; 
    addCustomElements; 

    hideTabBar method hides the original tabbar 
    And addCustomElements method will add the custom tabbar image as well as custom tabbar button also 


- (void)hideTabBar 
{ 
    for(UIView *view in self.tabBarController.view.subviews) 
    { 
     //  if([view isKindOfClass:[UITabBar class]]) 
     //  { 
     //   view.hidden = YES; 
     //   break; 
     //  } 

     if([view isKindOfClass:[UITabBar class]]) 
     { 
      [view setFrame:CGRectMake(view.frame.origin.x, 480, view.frame.size.width, view.frame.size.height)]; 
     } 
     else 
     { 
      [view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, 480)]; 
     } 


    } 
} 

-(void)addCustomElements 
{ 
    // Initialise our two images 
    UIImage *btnImage = [UIImage imageNamed:@"homet.png"]; 
    UIImage *btnImageSelected = [UIImage imageNamed:@"homehovert.png"]; 

    self.btn1 = [UIButton buttonWithType:UIButtonTypeCustom]; //Setup the button 
    btn1.frame = CGRectMake(28, 446, 25,28); // Set the frame (size and position) of the button) 
    [btn1 setBackgroundImage:btnImage forState:UIControlStateNormal]; // Set the image for the normal state of the button 
    [btn1 setBackgroundImage:btnImageSelected forState:UIControlStateSelected]; // Set the image for the selected state of the button 
    [btn1 setTag:0]; // Assign the button a "tag" so when our "click" event is called we know which button was pressed. 
    [btn1 setSelected:true]; // Set this button as selected (we will select the others to false as we only want Tab 1 to be selected initially 

    // Now we repeat the process for the other buttons 
    btnImage = [UIImage imageNamed:@"blogt.png"]; 
    btnImageSelected = [UIImage imageNamed:@"bloghovert.png"]; 
    self.btn2 = [UIButton buttonWithType:UIButtonTypeCustom]; 
    btn2.frame = CGRectMake(107, 448, 22,28); 
    [btn2 setBackgroundImage:btnImage forState:UIControlStateNormal]; 
    [btn2 setBackgroundImage:btnImageSelected forState:UIControlStateSelected]; 
    [btn2 setTag:1]; 

    btnImage = [UIImage imageNamed:@"networkt.png"]; 
    btnImageSelected = [UIImage imageNamed:@"networkhovert.png"]; 
    self.btn3 = [UIButton buttonWithType:UIButtonTypeCustom]; 
    btn3.frame = CGRectMake(180, 446, 35,29); 
    [btn3 setBackgroundImage:btnImage forState:UIControlStateNormal]; 
    [btn3 setBackgroundImage:btnImageSelected forState:UIControlStateSelected]; 
    [btn3 setTag:2]; 

    btnImage = [UIImage imageNamed:@"contactt.png"]; 
    btnImageSelected = [UIImage imageNamed:@"contacthovert.png"]; 
    self.btn4 = [UIButton buttonWithType:UIButtonTypeCustom]; 
    btn4.frame = CGRectMake(262, 447, 32,28); 
    [btn4 setBackgroundImage:btnImage forState:UIControlStateNormal]; 
    [btn4 setBackgroundImage:btnImageSelected forState:UIControlStateSelected]; 
    [btn4 setTag:3]; 

    self.img1 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"tabbar.png"]] ; 
    img1.frame = CGRectMake(0, 440, 320, 40); 




    [self.tabBarController.view addSubview:img1]; 
    // Add my new buttons to the view 
    [self.tabBarController.view addSubview:btn1]; 
    [self.tabBarController.view addSubview:btn2]; 
    [self.tabBarController.view addSubview:btn3]; 
    [self.tabBarController.view addSubview:btn4]; 

    // Setup event handlers so that the buttonClicked method will respond to the touch up inside event. 
    [btn1 addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside]; 
    [btn2 addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside]; 
    [btn3 addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside]; 
    [btn4 addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside]; 
} 
0
// not supported on iOS4  
UITabBar *tabBar = [tabController tabBar]; 
if ([tabBar respondsToSelector:@selector(setBackgroundImage:)]) 
{ 
    // set it just for this instance 
    [tabBar setBackgroundImage:[UIImage imageNamed:@"tabbar_brn.jpg"]]; 

    // set for all 
    // [[UITabBar appearance] setBackgroundImage: ... 
} 
else 
{ 
    // ios 4 code here 
} 
1

Come accennato prima su iOS 5 Vorrei suggerire di utilizzare l'immagine di sfondo:

UITabBar *tabBar = tabController.tabBar; 
if ([tabBar respondsToSelector:@selector(setBackgroundImage:)]) { 
    tabBar.backgroundImage = [UIImage imageNamed:@"TabBackground.png"]; 
} 

Usare sempre un assegno come respondsToSelector anziché esplicito controllo della versione. Ciò si traduce in un codice più sicuro e più a prova di futuro.

Su iOS 4 suggerisco di utilizzare il metodo -[UITabBar drawRect:], preferibilmente in una sottoclasse. Quindi in Interface Builder è possibile impostare la classe personalizzata UITabBar s (solitamente in MainWindow.xib) nella sottoclasse personalizzata.

Tuttavia, se non si utilizza un MainWindow.xib, e come i modelli di codice di iOS 5 si genera il tuo UITabBarController nel codice, si può solo sovrascrivere il metodo drawRect: utilizzando una categoria a UITabBar.

// UITabBar+CustomBackground.h 
@interface UITabBar (CustomBackground) 
@end 

// UITabBar+CustomBackground.m 
@implementation UITabBar (CustomBackground) 
- (void) drawRect:(CGRect)frame { 
    [[UIColor redColor] set]; 

    CGContextRef ctx = UIGraphicsGetCurrentContext(); 
    CGContextFillRect(ctx, [self bounds]); 
} 
@end 

Questo funziona solo su sistemi iOS 4.xe precedenti, ma va bene perché abbiamo già coperto iOS 5.

1

Devi solo identificare ogni caso, controllando la versione con -respondToSelector come detto Vinodh. Ti suggerisco di creare una categoria su UITabBar e farlo in modo semplice. Così il codice avrà questa forma:

// UITabBar+Custom.h 

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

    @interface UITabBar (Custom) 
    -(void)setTabBarBackground:(UIImage *)backgroundImage; 
    @end 

e il file .m:

// UITabBar+Custom.m 

    #import "UITabBar+Custom.h" 
    #import <objc/runtime.h> 

    static char *backgroundImageKey; 

    -(void)setImage:(UIImage *)anImage { 
      objc_setAssociatedObject(self, &backgroundImageKey, 
       anImage, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 
      [self setNeedsDisplay]; 
    } 

    -(UIImage *)image { 
      return objc_getAssociatedObject(self, &backgroundImageKey); 
    } 

    -(void)setTabBarBackground:(UIImage *)backgroundImage { 
     if([self respondsToSelector:@selector(setBackgroundImage:)]) { 
       [self setBackgroundImage:backgroundImage]; 
     } else { 
       [self setImage:backgroundImage]; 
     } 
    } 

    -(void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx { 
     UIGraphicsPushContext(ctx); 
     UIImage *currentImage = [self image]; 
     CGContextTranslateCTM(ctx, 0, currentImage.size.height); 
     CGContextScaleCTM(ctx, 1.0, -1.0); 

     CGContextDrawImage(ctx, self.bounds, currentImage.CGImage); 
     UIGraphicsPopContext(); 
    } 

Il -drawLayer:inContext sarà disegnare l'immagine di sfondo veloce.

1

Come ho risposto in precedenza, senza l'aggiunta di UIView è possibile aggiungere l'immagine di sfondo a un UITabBar, un'immagine che potrebbe scomparire quando si chiama [tabBar setNeedsDisplay], così ho pensato di disegnare l'immagine in -drawLayer:layer inContext:ctx (il -drawInRect:rect non si chiama). Tuttavia, se si può evitare di chiamare [tabBar setNeedsDisplay], c'è un modo semplice di fare questo:

// UITabBar+Custom.m 

#import "UITabBar+Custom.h" 
#import <QuartzCore/QuartzCore.h> 

-(void)setTabBarBackground:(UIImage *)backgroundImage { 
    if([self respondsToSelector:@selector(setBackgroundImage:)]) { 
      // ios 5+ 
      [self setBackgroundImage:backgroundImage]; 
    } else { 
      // ios 3.x/4.x 
      self.layer.contents = (id)backgroundImage.CGImage; 
    } 
} 
0
// Change the tab bar background 
UIImage* tabBarBackground = [UIImage imageNamed:@"tabbar.png"]; 
[[UITabBar appearance] setBackgroundImage:tabBarBackground]; 
Problemi correlati