2011-05-11 15 views
32

He optado por usar un UITableViewController sin una punta. Necesito una UIToolbar en la parte inferior con dos botones. ¿Cuál es la forma más simple de hacer eso?¿Cómo agregar una UIToolbar a UITableViewController programmatically?

P.S. Sé que puedo usar fácilmente un UIViewController y agregar un UITableView, pero quiero que las cosas se vean consistentes en toda la aplicación.

¿Alguien puede ayudar?

vi el siguiente ejemplo y no estoy seguro sobre su validez:

(void)viewWillAppear:(BOOL)animated { 
    [super viewWillAppear:animated]; 

    //Initialize the toolbar 
    toolbar = [[UIToolbar alloc] init]; toolbar.barStyle = UIBarStyleDefault; 

    //Set the toolbar to fit the width of the app. 
    [toolbar sizeToFit]; 

    //Caclulate the height of the toolbar 
    CGFloat toolbarHeight = [toolbar frame].size.height; 

    //Get the bounds of the parent view 
    CGRect rootViewBounds = self.parentViewController.view.bounds; 

    //Get the height of the parent view. 
    CGFloat rootViewHeight = CGRectGetHeight(rootViewBounds); 

    //Get the width of the parent view, 
    CGFloat rootViewWidth = CGRectGetWidth(rootViewBounds); 

    //Create a rectangle for the toolbar 
    CGRect rectArea = CGRectMake(0, rootViewHeight - toolbarHeight, rootViewWidth, toolbarHeight); 

    //Reposition and resize the receiver 
    [toolbar setFrame:rectArea]; 

    //Create a button 
    UIBarButtonItem *infoButton = [[UIBarButtonItem alloc] initWithTitle:@"back" 
                    style:UIBarButtonItemStyleBordered 
                    target:self 
                    action:@selector(info_clicked:)]; 

    [toolbar setItems:[NSArray arrayWithObjects:infoButton,nil]]; 

    //Add the toolbar as a subview to the navigation controller. 
    [self.navigationController.view addSubview:toolbar]; 

    [[self tableView] reloadData]; 
} 

(void) info_clicked:(id)sender { 

    [self.navigationController popViewControllerAnimated:YES]; 
    [toolbar removeFromSuperview]; 

} 
+0

necesidad de señalar que la línea más importante aquí es [sizeToFit barra de herramientas]; sin él - se muestra la barra de herramientas, pero no se aceptan las interacciones del usuario –

Respuesta

78

Lo más sencillo que hacer es construir su proyecto en la parte superior de un UINavigationController. Ya tiene una barra de herramientas, simplemente está oculta por defecto. Puede revelarlo al alternar la propiedad toolbarHidden, y su controlador de vista de tabla podrá usarlo siempre que esté en la jerarquía del controlador de navegación.

En delegado de la aplicación, o en el objeto delegado de la aplicación pasa el control, crear el controlador de navegación con su UITableViewController como el controlador de vista raíz:

- (void)application: (UIApplication *)application 
      didFinishLaunchingWithOptions: (NSDictionary *)options 
{ 
    MyTableViewController   *tableViewController; 
    UINavigationController  *navController; 

    tableViewController = [[ MyTableViewController alloc ] 
           initWithStyle: UITableViewStylePlain ]; 
    navController = [[ UINavigationController alloc ] 
          initWithRootViewController: tableViewController ]; 
    [ tableViewController release ]; 

    /* ensure that the toolbar is visible */ 
    navController.toolbarHidden = NO; 
    self.navigationController = navController; 
    [ navController release ]; 

    [ self.window addSubview: self.navigationController.view ]; 
    [ self.window makeKeyAndVisible ]; 
} 

A continuación, establecer los elementos de la barra de herramientas en su objeto MyTableViewController:

- (void)viewDidLoad 
{ 
    UIBarButtonItem   *buttonItem; 

    buttonItem = [[ UIBarButtonItem alloc ] initWithTitle: @"Back" 
              style: UIBarButtonItemStyleBordered 
              target: self 
              action: @selector(goBack:) ]; 
    self.toolbarItems = [ NSArray arrayWithObject: buttonItem ]; 
    [ buttonItem release ]; 

    /* ... additional setup ... */ 
} 
+5

Este es un consejo increíble. Nunca supe que UINavigationController tiene una barra de herramientas que está oculta de forma predeterminada. Ya lo estaba usando así que esto fue una gran ventaja. También gracias por tomarse el tiempo para explicar realmente todo. – jini

6

También puede simplemente marcar la opción "muestra la barra de herramientas" en NavigationController attributes inspector.

+0

Pero luego está activado en todas las vistas que terminan usando el código de todos modos en aquellas vistas donde no se debe utilizar la barra de herramientas. –

1

Aquí está un ejemplo sencillo, que puede ayudar a

UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; 
    UIBarButtonItem *trashItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(deleteMessages)]; 
    UIBarButtonItem *composeItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCompose target:self action:@selector(composeMail)]; 
    NSArray *toolbarItems = [NSMutableArray arrayWithObjects:spaceItem, trashItem,spaceItem,composeItem,nil]; 
    self.navigationController.toolbarHidden = NO; 
    [self setToolbarItems:toolbarItems]; 

Gracias, prodeveloper

Cuestiones relacionadas