2010-07-26 6 views
22

Quiero hacer una pregunta sobre la UITableView del objetivo C. Estoy escribiendo un programa y me gustaría crear la UI mediante programación. Sin embargo, no sé cómo mostrar la tabla mediante programación. Ya tengo un NSMutableArray para almacenar los datos mostrados. Y creo un objeto UITableView *tableData;, ¿qué debo hacer para el próximo paso? Muchas gracias.¿Cómo se muestra el programa UITableView mediante programación?

Respuesta

38

después de escribir el código anterior, tiene que implementar el método delegado de UITableView.

estos son método delegado de carga UITableView

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    return [your array count]; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (cell == nil) { 

     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 

    } 

    // Configure the cell... 
    cell.textLabel.text = [yourarray objectAtIndex:indexPath.row]; 

    return cell; 

} 
+0

gracias por su respuesta. Pero no estoy usando la clase UIViewTable, solo uso la clase simple. ¿Te importaría decirme cómo agregar la matriz a la tabla o celda de la tabla? Gracias. – Questions

+0

@MarkSiu no es necesario implementar la clase UITableView Simplemente escriba el código para agregar UITableView en su función viewdidload y más arriba funcione su show table en su vista – priyanka

+0

gracias por su respuesta. He agregado las funciones anteriores en la clase .m. Sin embargo, descubrí que esas funciones no fueron llamadas por UITableView. ¿Cuándo se llaman las funciones? Gracias. – Questions

43

Algo como esto debe hacer el truco (suponiendo que se está ejecutando desde dentro de su controlador de vista y usted tiene una propiedad establecido para la vista de tabla):

tableView = [[[UITableView alloc] initWithFrame:CGRectMake(...) style:UITableViewStylePlain] autorelease]; 
tableView.dataSource = self; 
tableView.delegate = self; 

[self.view addSubview:tableView]; 

Cuando se reemplaza CGRectMake(...) con cualquier posición/tamaño te gustaría.

+0

gracias por su respuesta. Pero quiero preguntar, ¿dónde debería poner NSMutableArray? gracias. – Questions

+0

Almacenará la matriz en su controlador de vista y la usará en los métodos UITableViewDataSource. Por ejemplo, devolvería la longitud de la matriz en tableView: numberOfRowsInSection :. –

+0

gracias por su respuesta. Debido a que la interfaz de usuario contiene otros elementos, agrego UITableView como parte de ellos. Y no sé cómo llamar a UITableDataSource ya que la clase no es una clase de vista de tabla cuando la creo. ¿Te importaría decirme cómo importar o agregar los datos en la matriz? gracias. – Questions

21
  • crear una nueva clase que hereda de UIViewController.
  • Haga que se ajuste al protocolo UITableViewDataSource.
  • Declara tu vista de tabla.

Su archivo de cabecera debe ser como la siguiente:

@interface MyViewController : UIViewController <UITableViewDataSource> {  

} 

@property (nonatomic, retain) UITableView *tableView; 

@end 

En el método de la clase viewLoad:

  • Crear una vista de tabla utilizando initWithFrame. Utilice las dimensiones 320x460 para la altura completa. Quite 44 de altura si tiene una barra de navegación y 49 si tiene una barra de pestañas.
  • Crea una vista nueva.
  • Agregue la vista de tabla a la nueva vista.
  • Establezca la vista del controlador en la nueva vista.
  • Establezca el origen de datos de la vista de tabla en su instancia (uno mismo).
  • Implementar los dos métodos de fuente de datos requeridos: tableView: cellForRowAtIndexPath y tableView: numberOfRowsInSection

El archivo de aplicación debe ser como la siguiente:

#import "MyViewController.h" 

@implementation MyViewController 

@synthesize tableView=_tableView; 

- (void)dealloc 
{ 
    [_tableView release]; 

    [super dealloc]; 
} 

#pragma mark - View lifecycle 

- (void)loadView 
{ 
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 460.0) style:UITableViewStylePlain]; 
    self.tableView = tableView; 
    [tableView release];  

    UIView *view = [[UIView alloc] init]; 
    [view addSubview:self.tableView]; 
    self.view = view; 
    [view release]; 

    self.tableView.dataSource = self; 
} 

- (void)viewDidUnload { 
    self.tableView = nil; 

    [super viewDidUnload]; 
} 

#pragma mark - Table view data source 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *MyCellIdentifier = @"MyCellIdentifier"; 

    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:MyCellIdentifier]; 

    if(cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyCellIdentifier] autorelease]; 
    } 

    return cell; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    return 5; 
} 

@end 
2

Quizás es también muy útil para todos aquellos nuevos en ti ahí.

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // init table view 
    tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain]; 

    //or, you may do that 
    //tableView = [[UITableView alloc] init]; 
    //tableView.frame = CGRectMake:(5 , 5 , 320 , 300); 

    // must set delegate & dataSource, otherwise the the table will be empty and not responsive 
    tableView.delegate = self; 
    tableView.dataSource = self; 

    tableView.backgroundColor = [UIColor cyanColor]; 

    // add to canvas 
    [self.view addSubview:tableView]; 
} 

#pragma mark - UITableViewDataSource 
// number of section(s), now I assume there is only 1 section 
- (NSInteger)numberOfSectionsInTableView:(UITableView *)theTableView 
{ 
    return 1; 
} 

// number of row in the section, I assume there is only 1 row 
- (NSInteger)tableView:(UITableView *)theTableView numberOfRowsInSection:(NSInteger)section 
{ 
    return 1; 
} 

// the cell will be returned to the tableView 
- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *cellIdentifier = @"HistoryCell"; 

    // Similar to UITableViewCell, but 
    JSCustomCell *cell = (JSCustomCell *)[theTableView dequeueReusableCellWithIdentifier:cellIdentifier]; 
    if (cell == nil) { 
     cell = [[JSCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; 
    } 
    // Just want to test, so I hardcode the data 
    cell.descriptionLabel.text = @"Testing"; 

    return cell; 
} 

@end 
+0

para gente nueva (yo), para copiar/pegar en una aplicación genérica, cambiar 'JSCustomCell' a 'UITableViewCell', cambiar 'cell.descriptionLabel.text' a 'cell.textLabel.text'. recuento de devolución de los elementos de su matriz para 'numberOfRowsInSection'. recordatorio para declarar métodos de delegado (creo que así se llama) en el archivo .h, ''. (gracias Abhay) – tmr

Cuestiones relacionadas