2009-03-24 9 views
32

Tengo un UITabBarController donde el controlador de vista predeterminado es un UINavigationController. Quiero poder ocultar la UITabBar del UITabBarController cuando presiono una determinada vista en el UINavigationController.Ocultar UITabBar al presionar un UIView

He intentado añadir:

delegate.tabBarController.hidesBottomBarWhenPushed = YES; 

en mi UINavigationController antes empujo la vista, pero eso no parece hacer el truco.

¿Algún consejo sobre lo que debería hacer o si es posible? ¡Gracias por adelantado!

Respuesta

94

Esto es mejor:

viewController.hidesBottomBarWhenPushed = YES; 
[self.navigationController pushViewController:viewController animated:YES]; 

Usted tiene que fijar hidesBottomBarWhenPushed = SI en el controlador que se va a empujar a la vista ...

+2

Esto es definitivamente mejor. ¡Gracias! – givp

+4

Una cosa para recordar: debe poner el código anterior ANTES de presionarlo al controlador. Eso es justo después de la línea de inicialización. NO funcionará si pones esto en viewDidLoad o en un lugar similar ... – Lukasz

+0

Muy bien, resolvió mis horas horas horas !!! – Rahul

0

Resulta que si configura la vista hidesBottomBarWhenPushed:YES oculta la barra cuando aparece la vista (duh de mi parte). Lo estaba asignando al UITabBarController, que no tiene demasiado sentido cuando lo piensas.

[self.view hidesBottomBarWhenPushed:YES]; 
[super pushViewController:viewController animated:animated]; 
+4

que está mal. ambos métodos se deben aplicar al controlador de vista que va a insertar. – hfossli

+1

Esta es una respuesta muy incorrecta. –

2

Así es como se obtiene que esto funcione :

En el Application Delegate crea el UITabBarController. Luego crea un UINavigationController con su controlador raíz como el controlador de vista que desea en la pestaña en particular. Luego inserte el UINavigationController en la matriz "viewControllers" del UITabBarController. de este modo:

ViewControllerForTab1 *tab1Controller = [[ViewControllerForTab1 alloc] initWithNibName:@"ViewControllerForTab1"]; 

UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:tab1Controller]; 

[tab1Controller release]; 


UITabBarController *tabBarController = [[UITabBarController alloc] init]; 
tabBarController.viewControllers = [NSArray arrayWithObjects: navController, nil]; 

[navController release]; 


[self.window addSubView:tabBarController.view]; 

De esta manera se puede establecer el "hidesBottomBarWhenPushed" propiedad de "YES" en cualquier controlador de vista dentro de esa UINavigationController y va a ocultar el UITabBar.

Espero que ayude!

1

Voy a dejar aquí mi solución para esto:

#define FRAME_HIDDEN CGRectMake(0, 0, 768, 1073) //1073 = 1024 (screen) + 49 (UITabBar) 
#define FRAME_APPEAR CGRectMake(0, 0, 768,1024) 

-(void) setHidden: (BOOL) hidden{ 
    CGRect frame = (hidden)? FRAME_HIDDEN : FRAME_APPEAR; 
    [self.tabBarController.view setFrame:frame]; 
    [self.tabBarController.tabBar setHidden:hidden]; 
} 

llama al método 'setHidden' donde lo necesite! Estoy usando esto y el 'Patrón Singleton', entonces mis subvistas pueden ocultar la UITabBar en su Superview

+0

Ocultar como tal no funciona. Bueno, funciona, pero deja un fondo negro donde solía estar la tabbar, que no es accesible desde mi punto de vista. Mover la barra de pestañas más allá de la parte visible de la pantalla hace el truco. Sin embargo, esto tiene un impacto en los límites de la pantalla que puede tener efectos secundarios a otras partes de la aplicación. –

+0

Lo sentimos, el comentario anterior fue incorrecto y no puedo editarlo más. Cambiar de forma similar el marco de la vista de tabBarController tiene un cierto impacto en el layoout de las subViews en comparación con la solución (para mí insuficiente) que utiliza la barra ocultaBottomBarCuando se empuja. Todavía estoy investigando y puedo publicar una actualización aquí, a menos que el error esté en algún lugar de mis cálculos. –

+0

Bueno, observé algunos efectos secundarios que pueden ser de interés: en mi opinión, tenía una pequeña vista secundaria en la parte inferior de la pantalla completa.Ubicados asumiendo que no habrá una barra de pestañas y, por lo tanto, utilizando el espacio que generalmente ocupa la barra de pestañas. Agregué esta sub vista en IB. En IB, coserá cada vista en uno o más bordes o en el centro de la pantalla/subvista para fines de autosizing. Este tipo de automatiza el cambio de orientación. Sin embargo, reubicó mi subvista junto con la barra de pestañas en algún lugar debajo de la pantalla. Solo tenga en cuenta el autosizing. –

3

He descubierto cómo resolver esto, me encontré con el mismo problema, pero Apple también nos dice cómo hazlo en la muestra llamada: "The Elements" (http://developer.apple.com/library/ios/#samplecode/TheElements/Introduction/Intro.html)

Consulta la función a continuación sobre cómo hacerlo, ¡agrega esto a la función de inicio de la vista que deseas insertar!

-(id) init { 
    if(self = [super init]) { 
     self.hidesBottomBarWhenPushed = YES; 
    } 
    return self; 
} 

Se ocultará automáticamente la barra de pestañas, como la aplicación de fotos hace en su iPhone. Y cuando navegue hacia atrás, la vista principal mostrará nuevamente la barra de tabulación.

Buena suerte

+0

Esto funciona muy bien para mí. Mejor que cualquier otra solución hasta el momento – rpgmaker

3

He probado la mayoría de las soluciones sugeridas.Al final ninguno de ellos funcionó para mí.

hideTabBarWhenPushed oculta la barra de pestañas no solo para el controlador de vista que se inserta a continuación, sino para todos los controladores de vista que se insertan dentro. Para aquellos que sí quiero que vuelva a aparecer el controlador de la barra de pestañas.

La solución de Orafaelreis (ver más arriba) parecía ser la más adecuada. Pero su intento solo funcionó con estrictas orientaciones de retratos, ni siquiera para el revés. Así que tuve que arreglarlo. Esto es lo que finalmente obtuve:

#define kTabBarHeight    49 // This may be different on retina screens. Frankly, I have not yet tried. 

- (void) hideTabBar:(BOOL)hide { 

    // fetch the app delegate 
    AppDelegate   *delegate = [[UIApplication sharedApplication] delegate]; 

    // get the device coordinates 
    CGRect    bounds  = [UIScreen mainScreen].bounds; 
    float    width; 
    float    height; 

    // Apparently the tab bar controller's view works with device coordinates 
    // and not with normal view/sub view coordinates 
    // Therefore the following statement works for all orientations. 
    width     = bounds.size.width; 
    height     = bounds.size.height; 

    if (hide) { 

     // The tab bar should be hidden too. 
     // Otherwise it may flickr up a moment upon rotation or 
     // upon return from detail view controllers. 
     [self.tabBarController.tabBar setHidden:YES]; 

     // Hiding alone is not sufficient. Hiding alone would leave us with an unusable black 
     // bar on the bottom of the size of the tab bar. 
     // We need to enlarge the tab bar controller's view by the height of the tab bar. 
     // Doing so the tab bar, although hidden, appears just beneath the screen. 
     // As the tab bar controller's view works in device coordinations, we need to enlarge 
     // it by the tab bar height in the appropriate direction (height in portrait and width in landscape) 
     // and in reverse/upside down orientation we need to shift the area's origin beyond zero. 
     switch (delegate.tabBarController.interfaceOrientation) { 
      case UIInterfaceOrientationPortrait: 
       // Easy going. Just add the space on the bottom. 
       [self.tabBarController.view setFrame:CGRectMake(0,0,width,height+kTabBarHeight)]; 
       break; 

      case UIInterfaceOrientationPortraitUpsideDown: 
       // The bottom is now up! Add the appropriate space and shift the rect's origin to y = -49 
       [self.tabBarController.view setFrame:CGRectMake(0,-kTabBarHeight,width,height+kTabBarHeight)]; 
       break; 

      case UIInterfaceOrientationLandscapeLeft: 
       // Same as Portrait but add the space to the with but the height 
       [self.tabBarController.view setFrame:CGRectMake(0,0,width+kTabBarHeight,height)]; 
       break; 

      case UIInterfaceOrientationLandscapeRight: 
       // Similar to Upside Down: Add the space and shift the rect. Just use x and with this time 
       [self.tabBarController.view setFrame:CGRectMake(0-kTabBarHeight,0,width+kTabBarHeight,height)]; 
       break; 

      default: 
       break; 
     } 
    } else { 
     // reset everything to its original state. 
     [self.tabBarController.view setFrame:CGRectMake(0,0,width,height)]; 
     [self.tabBarController.tabBar setHidden:NO]; 
    } 

    return; 
} 


- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation{ 

    // It is important to call this method at all and to call it here and not in willRotateToInterfaceOrientation 
    // Otherwise the tab bar will re-appear. 
    [self hideTabBar:YES]; 

    // You may want to re-arrange any other views according to the new orientation 
    // You could, of course, utilize willRotateToInterfaceOrientation instead for your subViews. 
} 

- (void)viewWillAppear: (BOOL)animated { 

    // In my app I want to hide the status bar and navigation bar too. 
    // You may not want to do that. If so then skip the next two lines. 
    self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent; 
    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide]; 

    [self hideTabBar: YES]; 

    // You may want to re-arrange your subviews here. 
    // Orientation may have changed while detail view controllers were visible. 
    // This method is called upon return from pushed and pulled view controllers. 

    return; 
} 

- (void)viewWillDisappear: (BOOL)animated {  

    // This method is called while this view controller is pulled 
    // or when a sub view controller is pushed and becomes visible 
    // Therefore the original settings for the tab bar, navigation bar and status bar need to be re-instated 

    [self hideTabBar:NO]; 

    // If you did not change the appearance of the navigation and status bar in viewWillAppear, 
    // then you can skip the next two statements too. 
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack; 
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide]; 

    return; 
} 

Los comentarios en línea deben explicar el razonamiento de cada afirmación. Sin embargo, puede haber formas más inteligentes de codificarlo.

Hay un efecto secundario junto con la ocultación de la barra de estado y la barra de navegación, que no quiero ocultarles. 1. Cuando regrese de este controlador de navegación al controlador de navegación llamante, la barra de estado y la barra de navegación del controlador llamante se superponen hasta que el dispositivo se gire una vez o hasta que la pestaña relacionada haya sido elegida nuevamente después de que haya otra pestaña al frente. 2. Cuando el controlador de vista llamante es una vista de tabla y cuando el dispositivo está en modo apaisado al volver a la mesa, la tabla se muestra con la orientación adecuada para el paisaje, pero se muestra como si fuera un retrato. La esquina superior izquierda está bien, pero algunas celdas de tabla más barra de pestañas están ocultas debajo de la pantalla. En el lado derecho hay algo de espacio libre. Esto también se soluciona al rotar el dispositivo nuevamente.

Te mantendré actualizado una vez que encontré soluciones para estos errores menores pero desagradables.

3

cuando se trabaja con guión gráfico es fácil de controlador de vista de configuración que ocultar la barra de pestañas de empuje, en el controlador de vista de destino simplemente seleccione esta casilla:
enter image description here

0

en el primer UIViewController "FirstItemViewController"

@IBAction func pushToControllerAction(sender: AnyObject) { 
    self.hidesBottomBarWhenPushed = true 
    self.performSegueWithIdentifier("nextController", sender: self) 
} 

en la siguiente UIViewController "ExampleViewController" `

override func willMoveToParentViewController(parent: UIViewController?) { 
     if parent == nil { 
      var viewControllers = self.navigationController!.viewControllers 
      if ((viewControllers[viewControllers.count - 2]).isKindOfClass(FirstItemViewController.self)) { 
       (viewControllers[viewControllers.count - 2] as! FirstItemViewController).hidesBottomBarWhenPushed = false 
      } 
     } 
} 

Mire esta respuesta https://stackoverflow.com/a/36148064/3078925

Cuestiones relacionadas