2011-04-20 5 views
7

Actualmente estoy escribiendo mi primera aplicación para iPhone, pero he tenido un problema. Tengo una vista que contiene una UITableView. Esta es la primera vez que intento esto, y este es el comportamiento que intento lograr:Llamar a una nueva vista al seleccionar una fila en un 'UITableView'

Cuando el usuario selecciona una de las filas, me gustaría que llamara a una nueva vista, llevando al usuario a una página diferente que muestra información en referencia a lo que han seleccionado.

Lo tengo actualmente, así que cuando el usuario selecciona una fila, muestra un UIAlert en la misma vista, pero esto no satisface mis necesidades. Configuré UITableView a través del constructor de la interfaz e ingresé el siguiente código en mi archivo .m para configurarlo.

- (NSInteger)tableView:(UITableView *)tableView 
numberOfRowsInSection:(NSInteger)section { 
    //return the value 
    return 10; 
} 

//now we define the cells. 
- (UITableViewCell *)tableView:(UITableView *)tableView 
     cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    // Identifier for retrieving reusable cells. 
    static NSString *cellIdentifier = @"MyCellIdentifier"; 

    // Attempt to request the reusable cell. 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 

    // No cell available - create one 
    if(cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
             reuseIdentifier:cellIdentifier]; 
    } 

    // Set the text of the cell to the row index. 
    cell.textLabel.text = [NSString stringWithFormat:@"iPad %d", indexPath.row]; 

    return cell; 
} 

Esto crea una lista de diez filas. Los siguientes códigos me dan mi UIAlert cuando se toca, sin embargo, quiero eliminar esto y hacer que llame a una nueva vista de mi elección;

- (void)tableView:(UITableView *)tableView 
didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 

    // Show an alert with the index selected. 
    UIAlertView *alert = [[UIAlertView alloc] 
          initWithTitle:@"iPad Selected"       
          message:[NSString stringWithFormat:@"iPad %d", indexPath.row]      
          delegate:self  
          cancelButtonTitle:@"OK"   
          otherButtonTitles:nil]; 
    [alert show]; 
    [alert release]; 

} 

¿Alguien puede ayudar con este último fragmento de código? la vista que quiero que llame se llama 'ProteinView'.

Respuesta

3

Muy bien, lo que tenemos que hacer es utilizar uno de los métodos de UITableView que ya están disponibles para nosotros. Haremos lo siguiente.

- (void)tableView:(UITableView *)tableView 
didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 

ProteinView *detailViewController = [[ProteinView alloc] initWithNibName:@"ProteinView" bundle:nil]; 

     // It is here we'd pass information from the currently selected UITableViewCell to the ProteinView. 
     // An example of this is the following. 

     // I would do it like this, but others would differ slightly. 
     NSString *titleString = [[[NSString alloc] initWithFormat:@"iPad %d",indexPath.row] autorelease]; 

     // title is an object of detailViewController (ProteinView). In my own instances, I have always made a NSString which in viewDiDLoad is made the self.navigationBar.title string. Look below for what my ProteinView.m and .h would look like. 
     detailViewController.stringTitle = titleString; 
     // ... 
     // Pass the selected object to the new view controller. 
     [self.navigationController pushViewController:detailViewController animated:YES]; 
     [detailViewController release]; 
} 

EDITAR

// -------- ProteinView.m -------- // 

- (void)viewDidLoad { 

[super viewDidLoad]; 
// Do any additional setup after loading the view from its nib. 

// Here we set the navigationItem.title to the stringTitle. stringTitle is declared in the .h. Think of it as a global scope variable. It is also propertised in the .h and then synthesized in the .m of ProteinView. 
self.navigationItem.title = stringTitle; 
} 

no he compilado esto, así que no sé si funcionará plenamente. ¡Pero esa es definitivamente la forma más rápida y fácil de hacerlo!

+0

Esta es una respuesta correcta, pero (a) presume que OP usa un controlador de vista de navegación, y (b) realmente no explica las diferentes partes involucradas: nuevos controles de vista, XIB y el 'título 'atributo. Tal vez elaborar un poco? – Tim

+0

He usado ese ejemplo, compilado, etc., la UIToolBar muestra bien. pero cuando se toca una fila, la aplicación falla. #Dismayed! –

+0

Parece dar una advertencia basada en ese [NSString withFormat: pieza de código. Vea la captura de pantalla si alguien todavía está leyendo esto :-) - http://d.pr/AKNb –

1

Se podría presentar el punto de vista modal como esto

YourViewController2 *viewController2 = [[YourViewController2 alloc]initWithNibName:@"YourViewController2" bundle:nil]; 
[self presentModalViewController:viewController2 animated:YES]; 

¿Tiene más de un fin de presentar? Si es así, deberá crear una matriz con los nombres, pasarla a la vista de tabla y luego presentar la vista correcta para la fila seleccionada en función de indexPath.row.

0

tendrá que abrir su MainWindow.xib y agregarle un controlador de navegación. A continuación, agregue una salida de controlador de navegación a su delegado de aplicación y conéctelos. Luego, deberá configurar la vista del controlador de navegación como vista de la ventana principal.

Puede agregar una vista de tabla a cualquier aplicación de iPhone con bastante facilidad, simplemente creando una nueva subclase UITableViewController desde el comando Archivo -> Nuevo.

Incluso si sigue esta ruta, le sugiero que cree un nuevo proyecto basado en navegación para usar como plantilla/hoja de referencia. UITableView – Creating a Simple Table View

+0

Mike, Mike, Mike - todo eso suena maravilloso, sin embargo, sabes que literalmente no tengo idea de lo que estás hablando jaja. Acabo de leer tu tweet, así que si tienes tiempo, ¿puedes resolver un pequeño proyecto de ejemplo? Mal correo ahora –

+0

jajaja, sé que es un poco molesto, pero comenzar un nuevo proyecto con el tutorial que publiqué. Sé que crees que es fácil de hacer, pero puede ser complicado intentar agregar controles de navegación adicionales a un proyecto existente. si completa el tutorial (parte 1 y 2), tendrá un resumen de lo que quiere hacer, luego puede agregar lo que sabe a su proyecto o agregar su proyecto al tutorial de muestra – d4ndym1k3

+0

De hecho, tiene razón. Lo intentaré esta noche, quizás deba pensar en una nueva forma de presentar lo que quiero mostrar. Gracias a todos –

Cuestiones relacionadas