2012-10-02 25 views

Respuesta

2

Primero crea una vista para guardar todo. continuación, agregar un marco de establecer mediante programación UITableView y UIToolbar para que aparezca bajo el tableview .Add el campo de texto de la barra de herramientas

UIView *placeholderView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 400, 440)]; 
    UITableView *tv=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, 400, 400)]; 
    [placeholderView addSubview:tv]; 
    UIToolbar *toolBar=[[UIToolbar alloc]initWithFrame:CGRectMake(0, 400, 400, 40)]; 
    [placeholderView addSubview:toolBar]; 
5

Uso UIViewController una subclase en lugar de UITableViewController subclase.

Debe ser algo como esto:

@interface ChatViewController : UIViewController 
@end 


#import "ChatViewController.h" 

@interface ChatViewController() <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate> 
@property (nonatomic, strong) UITableView *tableView; 
@property (nonatomic, strong) UIToolbar *toolbar; 
@property (nonatomic, strong) UITextField *textField; 
@end 

@implementation ChatViewController 

-(UITableView *)tableView 
{ 
    if (!_tableView) { 
     _tableView = [UITableView alloc] init]; 
     CGRect frame = self.view.bounds; 
     frame.size.height = frame.size.height - 44; 
     _tableView.frame = frame; 
     _tableView.delegate = self; 
     _tableView.dataSource = self; 
    } 
    return _tableView; 
} 

-(UIToolbar *)toolbar 
{ 
    if (!_toolbar) { 
     _toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0,self.tableView.frame.size.height,self.view.frame.size.width, 44)]; 
    self.textField = [[UITextField alloc] initWithFrame:CGRectMake(0,0,_toolbar.frame.size.width -20)]; 
    self.textField.delegate = self; 
    UIBarButtonItem *textFieldItem = [[UIBarButtonItem alloc] initWithCustomView:self.textField]; 
    UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace 
                        target:nil 
                        action:nil]; 
    // You'll need to add a button to send you text 
    _toolbar.items = [NSArray arrayWithObjects:flexibleSpace, textFieldItem, flexibleSpace, nil]; 
    } 
    return _toolbar; 
} 

-(void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    [self.view addSubview:self.tableView]; 
    [self.view addSubview:self.toolbar]; 
    [[NSNotificationCenter defaultCenter] addObserver:self 
              selector:@selector(keyboardWillHideOrShow:) 
               name:UIKeyboardWillHideNotification 
               object:nil]; 
    [[NSNotificationCenter defaultCenter] addObserver:self 
              selector:@selector(keyboardWillHideOrShow:) 
               name:UIKeyboardWillShowNotification 
               object:nil]; 
} 

- (void)viewDidUnload 
{ 
    [[NSNotificationCenter defaultCenter] removeObserver:self]; 
    [super viewDidUnload]; 
} 


- (void)keyboardWillHideOrShow:(NSNotification *)note 
{ 
    NSDictionary *userInfo = note.userInfo; 
    NSTimeInterval duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]; 
    UIViewAnimationCurve curve = [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue]; 

    CGRect keyboardFrame = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue]; 
    CGRect keyboardFrameForToolbar = [self.toolbar.superview convertRect:keyboardFrame fromView:nil]; 
    CGRect keyboardFrameForTableView = [self.tableView.superview convertRect:keyboardFrame fromView:nil]; 

    CGRect newToolbarFrame = self.toolbar.frame; 
    newToolbarFrame.origin.y = keyboardFrameForToolbar.origin.y - newToolbarFrame.size.height; 

    CGRect newTableViewFrame = self.tableView.frame; 
    newTableViewFrame.size.height = keyboardFrameForTableView.origin.y - newToolbarFrame.size.height; 

    [UIView animateWithDuration:duration 
          delay:0 
         options:UIViewAnimationOptionBeginFromCurrentState | curve 
        animations:^{self.toolbar.frame = newToolbarFrame; 
         self.tableView.frame =newTableViewFrame;} 
        completion:nil]; 
} 

Esto se ocuparía de trazar los puntos de vista y la animación de la apariencia del teclado. Deberá gestionar los métodos de delegado y origen de datos para la vista de tabla y el campo de texto.

+0

Buena respuesta, parece prometedora pero supongo que no hay ningún inconveniente de usar 'UITableViewController' siempre que las dimensiones de la vista de tabla y la barra de herramientas estén configuradas correctamente. Me pregunto por qué sugirió no usar 'UITableViewController'? –

+0

'UITableViewController' puede ser complicado si intenta agregar subvistas a su vista principal, que es una vista de tabla. – Moxy

26

¡Acabo de encontrar un truco mejor!

  1. Asegúrese de que no hay barra de navegación (de sus intentos fallidos)
  2. arrastrar y soltar una "barra de botones de artículos" (Xcode mágicamente colocarlo para usted en la parte inferior)
  3. NOTA: Si ejecuta la aplicación ahora, ¡no verá nada! (A fin de mantener la lectura)
  4. añadir la siguiente línea de código bajo viewDidLoad:

self.navigationController.toolbarHidden = NO;

¡Hecho!

+0

¡Esto es exactamente lo que estaba buscando! –

+0

¡Lo has clavado! Un millón de gracias. Lo tenía originalmente, y luego lo eliminé y olvidé cómo lo devolví, lol. – pqsk

+0

¡Funciona! También asegúrate de que el color del tinte en UIBarButtonItem no sea blanco ... – rjobidon

1

No es genial en algunos aspectos, pero lo resolví utilizando una Vista de contenedor en un Controlador de vista adicional.

Storyboard screenshot

El Intermedio VC a la Tabla VC segue es "Insertar"

He utilizado este en lugar de la "Barra de herramientas de Nav Controller" solución, ya que estoy añadiendo esto a un diseño de aplicación existente con ~ 15 pantallas, y no estaba seguro de cómo configurar diferentes barras de herramientas en diferentes pantallas.

+0

Estoy de acuerdo en que esto no es genial, pero se trata simplemente de una omisión flagrante para IOS por el cual no puedes agregar una UIToolbar a un UIViewController sin antes incrustar ese UIVC en una UINavigationController. En mi situación, no puedo incorporar mis UIVC en un UINC debido a otras "características de diseño" del UINC. –

Cuestiones relacionadas