lunes, 18 de junio de 2012

Aprendiendo Objetive-C para IOS (Dia 10)


Guion del blog de curso de Objetive-C para IOS - DIA 10

nota: Esto es no es curso propiamente dicho, es un diario de autoaprendizaje de objetive-c, que me sirve para afianzar conocimientos, y de paso, tener un diario de referencia, con ejemplos propios de uso del lenguaje.

-------------

Vamos a ver como crear un UITableView en nuestro proyecto. Para eso, hacemos como siempre un nuevo proyecto, que tenga una single view, y añadimos a dicho proyecto un TableView desde el interface builder.





Una vez echo esto, asignamos los 2 outlets de la tabla, a nuestro FilesOwner, tal como nuestra la imagen


------------

Hacemos el outlet de dicha tabla en nuestro archivo ViewController.h, y nos creamos también un vector para guardar los diferentes elementos que queremos tener en nuestra tabla.

El archivo ViewController.h quedara así:

//
//  ViewController.h
//  Diario010
//
//  Created by david fraj blesa on 14/06/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>{
    
    //Creamos un array Mutable, para guardar un listado.
    NSMutableArray *listado;
    
}

@property (retain, nonatomic) IBOutlet UITableView *tableListado;

@end


Fijaos en estas lineas:

@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>{

Aquí nos estamos comprometiendo, mediante los dos protocolos UITableViewDelegate y  UITableViewDataSource, que implementaremos los métodos obligatorios que dictan dichos protocolos, como ya nos paso en el PickerView


Dicha implementación la haremos en el archivo ViewController.m, quedando el código así:

//
//  ViewController.m
//  Diario010
//
//  Created by david fraj blesa on 14/06/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "ViewController.h"

@implementation ViewController

@synthesize tableListado;

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
    
    //Inicializamos el vector que tendrá todos los objetos, y le damos elementos
    listado=[[NSMutableArray alloc] initWithObjects:@"Zaragoza", @"Huesca", @"Teruel", nil];
    
    //Podemos añadir asi
    [listado addObject:@"Valencia"];
    [listado addObject:@"Alicante"];
    
    //O podemos añadir con un bucle
    for(int i=0; i<10;i++){
        [listado addObject:[NSString stringWithFormat:@"Ciudad %i", i]];
    }
    
    
    
    
}

////////////////////
// COMO NOS HEMOS COMPROMETIDO, MEDIANTE LOS PROTOCOLOS 
//<UITableViewDelegate, UITableViewDataSource>, tenemos que 
//implementar los siguientes metodos, para poder hacer funcionar nuestra tabla
//Esto tambien pasaba cuando vimos el UIPickerView, y volvera a pasar
//Mas adelante con los map View por ejemplo

//Metodo para establecer el titulo de la tabla
-(NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return @"Titulo de tabla";
}

//Metodo para establecer el pie de la tabla
-(NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{
    return @"Pie de la tabla";
}

//Necesitamos decirle como llenar la tabla. Devolvera la celda 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    //En todos los ejemplos ponen la palabra static, pero no hace falta
    NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
   
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    // Configuramos la celda
    cell.textLabel.text = [listado objectAtIndex:indexPath.row];

    //Vamos a ponerle una imagen a la celda
    //Creamos un objeto de imagen, llamado icono
    UIImage *icono=[UIImage imageNamed:@"icono.jpg"];
    
    //Asignamos el objeto imagen llamado icono, a la celda
    cell.imageView.image=icono;
    
    //Devuelvo la celda
    return cell;
    
}

//Debemos decirle cuantos elementos tenemos
//llamaremos al metodo count de nuestro vector
-(NSInteger )tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [listado count];
}

//Vamos a implementar ahora, el metodo para que nos saque un UIAlertView, cuando pulsemos en uno de los elementos
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //Creamos un string para recoger lo que se mostrara
    NSString *texto=[listado objectAtIndex:[indexPath row]];
    
    //Creamos el alert
    UIAlertView *alerta=[[UIAlertView alloc] initWithTitle:@"Elemento seleccionado" message:texto delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
    
    //mostramos la alerta
    [alerta show];
    
    //liberamos recursos
    [alerta release];
    [texto release];
}


///////////////////
////////////////////////////////////
/////////////////////////////////////////////////


- (void)viewDidUnload
{
    [self setTableListado:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (void)dealloc {
    [tableListado release];
    [super dealloc];
}
@end


----------------------

Nota: La imagen que ponemos en cada celda, tiene que agregarse al proyecto

No hay comentarios:

Publicar un comentario