Respuesta

49

Ningún problema en absoluto, UITableViewController es una subclase de UIViewController. Y sucede que en iPhone OS 3.0 cualquier UIViewController(y subclases) puede funcionar junto con UINavigationController para proporcionar una barra de herramientas contextual.

Para que esto funcione es necesario:

  • Asegúrese de que utiliza un UINavigationController que contienen todos sus controladores de vista que necesita una barra de herramientas.
  • Establezca la propiedad toolbarsItems del controlador de vista que quiere una barra de herramientas.

Esto es casi tan fácil como configurar el título del controlador de vista, y debe hacerse de la misma manera. Lo más probable es anulando el inicializador initWithNibName:bundle:. A modo de ejemplo:

-(id)initWithNibName:(NSString*)name bundle:(NSBundle*)bundle; 
{ 
    self = [super initWithNibName:name bundle:bundle]; 
    if (self) { 
    self.title = @"My Title"; 
    NSArray* toolbarItems = [NSArray arrayWithObjects: 
     [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd 
                 target:self 
                 action:@selector(addStuff:)], 
     [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch 
                 target:self 
                 action:@selector(searchStuff:)], 
     nil]; 
    [toolbarItems makeObjectsPerformSelector:@selector(release)]; 
    self.toolbarItems = toolbarItems; 
    self.navigationController.toolbarHidden = NO; 
    } 
    return self; 
} 

También puede utilizar setToolbarItems:animated: en lugar de asignar a la propiedad toolbarItems, para agregar y quitar elementos de la barra de una manera animada sobre la marcha.

+0

¿Se requiere NavigationController? Quiero agregar una barra de herramientas a TableViewController que no es parte de un NavigationController. ¿Debo usar un NavigationController aunque solo haya una vista en él? –

+0

@sirjorj Sí, se requiere el 'UINavigationController' para obtener la gestión * free * de la barra de herramientas. Sin él, debe gestionar su propia instancia de vista 'UIToolbar'. – PeyloW

+0

¿Qué pasa si no quiero poner botones en esta barra de herramientas? En su lugar, quiero poner solo una imagen en el centro, ¿qué haría de manera diferente? Gracias. –

39

Con el fin de hacer la receta de PeyloW a trabajar, tenía que añadir la siguiente línea de código adicional:

self.navigationController.toolbarHidden = NO; 

Espero que ayude ...

+2

De acuerdo. Tuve que poner esa llamada en el método viewDidLoad, no en el reemplazo de initWithNibName. Entonces funciona genial –

+0

me acabas de salvar el día, gracias –

12
- (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]; 

    } 

Y en Swift 3:

override func viewDidAppear(_ animated: Bool) { 
    super.viewDidAppear(animated) 

    //Initialize the toolbar 
    let toolbar = UIToolbar() 
    toolbar.barStyle = UIBarStyle.default 

    //Set the toolbar to fit the width of the app. 
    toolbar.sizeToFit() 

    //Caclulate the height of the toolbar 
    let toolbarHeight = toolbar.frame.size.height 

    //Get the bounds of the parent view 
    let rootViewBounds = self.parent?.view.bounds 

    //Get the height of the parent view. 
    let rootViewHeight = rootViewBounds?.height 

    //Get the width of the parent view, 
    let rootViewWidth = rootViewBounds?.width 

    //Create a rectangle for the toolbar 
    let rectArea = CGRect(x: 0, y: rootViewHeight! - toolbarHeight, width: rootViewWidth!, height: toolbarHeight) 

    //Reposition and resize the receiver 
    toolbar.frame = rectArea 

    //Create a button 
    let infoButton = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.plain, target: self, action: #selector(infoClicked)) 

    toolbar.items = [infoButton] 

    //Add the toolbar as a subview to the navigation controller. 
    self.navigationController?.view.addSubview(toolbar) 
} 

func infoClicked() { 
    //Handle Click Here 
} 
+0

Esto funciona muy bien para mí. No pude agregar un 'UINavigationController', por lo que una barra de herramientas añadida manualmente era la única manera de hacerlo. ¡Gracias! – codingFriend1

+1

Agradable. Creo que esta debería ser la respuesta aceptada. Quería ** agregar una barra de herramientas a uitableviewcontroller **, sin habilitar uinavigationcontroller. – soemarko

Cuestiones relacionadas