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
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;
}
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.
gracias por su respuesta. Pero quiero preguntar, ¿dónde debería poner NSMutableArray? gracias. – Questions
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 :. –
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
- 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
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
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, '
- 1. Agregar celdas mediante programación a UITableView
- 2. UITextView selectedRange no se muestra cuando se establece mediante programación
- 3. Cómo seleccionar mediante programación una fila en UITableView en MonoTouch?
- 4. Ejecutar el programa antivirus mediante programación usando delphi
- 5. Cómo reiniciar mediante programación?
- 6. agregar un UITableView mediante programación a un UIViewController
- 7. UITableView: ¿Ejecuta el código cuando se muestra tableFooterView?
- 8. Iniciar un programa predeterminado en OSX mediante programación
- 9. ¿Cómo se lee el margen de ImageView mediante programación?
- 10. ¿Cómo establecer el tamaño NSView mediante programación?
- 11. Magento, ¿cómo deshabilitar el módulo mediante programación?
- 12. Mover el mouse mediante programación
- 13. ¿Se puede encontrar el valor de un algoritmo mediante programación mediante el análisis de sus perfs?
- 14. Cómo ejecutar NUnit mediante programación
- 15. Cómo agregar vistas a vistas mediante programación
- 16. Cómo programar una tarea mediante programación
- 17. Agregar PageControl mediante programación
- 18. Cómo agregar una referencia mediante programación
- 19. UITableView - ¿Mejor edición mediante enlace?
- 20. ¿Cómo añadir un NSTableView desplazable mediante programación
- 21. ¿Cómo obtener privilegios de root mediante programación?
- 22. ¿Se puede detectar el ruido blanco mediante programación?
- 23. mediante programación en C#
- 24. Cómo limitar el número de celdas que muestra UITableview?
- 25. Deshabilitar mediante programación el bloqueo de mayúsculas
- 26. Cómo calcular la integral indefinida mediante programación
- 27. Cómo cambiar el icono de un botón mediante programación?
- 28. Mover el cursor del ratón mediante programación
- 29. ¿Cómo detectar mediante programación el interruptor de silenciamiento del iPhone?
- 30. ¿Cómo se selecciona mediante programación la fila superior de JQGrid?
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
@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
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