“CheckBoxes” para iPhone

Share


Despues de buscar por toda la documentación algun control tipo checkBox decidi crear una aplicación sencilla que simule el comportamiento de un checkBox usango dos graficos: encendido y apagado. El ejemplo que desarrollaremos sera una lista de compras en un UITableView:

Para empezar crearemos una nuevo proyecto del tipo "Navigation-Based Application" que llamaremos ListaDeCompras, quiero resaltar que en este ejemplo no usaremos Interface Builder porque me parece que quedara mucho mas claro hacerlo todo mediante programacion:

Nos crearemos un nuevo archivo tipo UIViewController al que llamaremos ListaDeComprasViewController, por ahora no haremos nada con este archivo.

Al crear el proyecto se creo por defecto un archivo ListaDeComprasAppDelegate con la extension .h y .m, entremos a ListaDeComprasAppDelegate.h para inicializar nuestra ventana y su navigationController :

C++:
  1. @interface ListaDeComprasAppDelegate : NSObject
  2. {
  3.  UIWindow  *window;
  4.  UINavigationController    *navigationController;
  5. }
  6. @end

Ahora en ListaDeComprasAppDelegate.m aňadimos la vista del controlador a nuestra la ventana dentro del metodo applicationDidFinishLaunching.
Al inicializar el navegador vemos que se asigna un initWithRootViewController , en este caso una instancia de ListaDeComprasViewController que sera la vista que se mostrara al iniciar la aplicacion:

C++:
  1. - (void)applicationDidFinishLaunching:(UIApplication *)application
  2. {
  3.  ListaDeComprasViewController *controler = [[ListaDeComprasViewController alloc] init];
  4.  navigationController = [[UINavigationController alloc] initWithRootViewController:controler];
  5.  [controler release];
  6.  [window addSubview: navigationController.view];
  7. }

Ahora trabajemos con los archivos ListaDeComprasViewController .h y .m respectivamente. En ListaDeComprasViewController.h inicializaremos un tableView para mostrar nuestros datos y un array que contendra nuestra lista de compras de la siguiente manera:

C++:
  1. @interface ListaDeComprasViewController : UIViewController
  2. {
  3.  NSMutableArray    *listaDeCompras;
  4.  UITableView      *slTableView;
  5. }
  6. @end

Ahora, en el archivo ListaDeComprasViewController.m es donde debemos cargar toda nuesta vista, recordemos que no estamos usando IB asi que debemos usar el metodo loadView.
Empezamos creando una vista inicial a la que llamaremos contentView, luego crearemos un tableView que añadiremos a la vista principal.
Para el arreglo crearemos objetos con 2 variables: item y cantidad y un booleano que nos indique si el objeto esta seleccionado o no.

C++:
  1. - (void)loadView
  2. {
  3.  listaDeCompras = [[NSMutableArray alloc] init];
  4.  UIView *contentView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
  5.  self.view = contentView;
  6.  [contentView release];
  7. self.view.autoresizesSubviews = YES;
  8.  
  9. [listaDeCompras addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:@"Huevos", @"item", @"Una docena", @"cantidad", [NSNumber numberWithBool:NO], @"completado", nil]];
  10.  [listaDeCompras addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:@"Leche", @"item", @"1 litro", @"cantidad", [NSNumber numberWithBool:NO], @"completado", nil]];
  11.  [listaDeCompras addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:@"Azucar", @"item", @"5 kilos", @"cantidad", [NSNumber numberWithBool:NO], @"completado", nil]];
  12.  
  13. slTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
  14.  slTableView.delegate = self;
  15.  slTableView.dataSource = self;
  16.  slTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
  17.  slTableView.autoresizesSubviews = YES;
  18.  slTableView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
  19.  
  20. [slTableView reloadData];
  21.  [self.view addSubview:slTableView];
  22. }

Ahora para poder usar nuestro tableView usamos los metodos de UITableViewDelegate y UITableViewDataSource.
En el metodo cellForRowAtIndexPath insertamos los valores del array para cada celda y con un if-else determinamos si aparecera la imagen de apagado o encendido dependiendo de nuestro valor booleano. Y en el metodo didSelectRowAtIndexPath es donde este valor ira cambiando cada vez q seleccionemos una celda.

C++:
  1. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  2. {
  3.  return 1;
  4. }
  5. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  6. {
  7.  return [listaDeCompras count];
  8. }
  9.  
  10. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  11. {
  12.  NSNumber *newValue = [NSNumber numberWithBool:![[[listaDeCompras objectAtIndex:indexPath.row] objectForKey:@"completado"] boolValue]];
  13.  
  14. [[listaDeCompras objectAtIndex:indexPath.row] setObject:newValue forKey:@"completado"];
  15.  [tableView reloadData];
  16. }
  17.  
  18. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  19. {
  20.  NSMutableString *cellValue = [NSMutableString stringWithCapacity:[[[listaDeCompras objectAtIndex:indexPath.row] objectForKey:@"item"] length] + [[[listaDeCompras objectAtIndex:indexPath.row] objectForKey:@"cantidad"] length] + 3];
  21.  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ListaDeComprasCell"];
  22.  if (cell == nil)
  23.  {
  24.    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"ListaDeComprasCell"] autorelease];
  25.  }
  26.  
  27. [cellValue setString:[[listaDeCompras objectAtIndex:indexPath.row] objectForKey:@"item"]];
  28.  [cellValue appendString:@" ("];
  29.  [cellValue appendString:[[listaDeCompras objectAtIndex:indexPath.row] objectForKey:@"cantidad"]];
  30.  [cellValue appendString:@")"];
  31.  
  32. cell.selectionStyle = UITableViewCellSelectionStyleNone;
  33.  cell.text = cellValue;
  34.  if([[[listaDeCompras objectAtIndex:indexPath.row] objectForKey:@"completado"] boolValue])
  35.  {
  36.    cell.image = [UIImage imageNamed:@"encendido.png"];
  37.    cell.textColor = [UIColor grayColor];
  38.  }
  39.  else
  40.  {
  41.    cell.image = [UIImage imageNamed:@"apagado.png"];
  42.    cell.textColor = [UIColor blackColor];
  43.  }
  44.  
  45. cell.showsReorderControl = YES;
  46.  
  47. return cell;
  48. }

Finalmente hacemos dos cambios mas en el archivo infoplist borramos el nombre del archivo main.nib en Main nib file base name porque no estamos usandolo y dentro del archivo main.m hacemos el siguiente cambio para que nuestro proyecto llame a ListaDeComprasAppDelegate:

C++:
  1. int main(int argc, char *argv[]) {
  2.  
  3. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  4. int retVal = UIApplicationMain(argc, argv, nil, @"ListaDeComprasAppDelegate");
  5. [pool release];
  6. return retVal;
  7. }

Las imagenes de encendido y apagado las agregamos a la raiz del proyecto o podemos crear un directorio especial para nuestras imagenes, en ambos casos funciona de la misma manera. Espero que este ejemplo les haya servido y cualquier pregunta no duden en escribir.

banner ad

One Response to ““CheckBoxes” para iPhone”

  1. Ivang says:

    No consigo que se guarde el archivo.
    Podriais decirme si se tiene que configurar algo en el simulador del iphone para poner un directorio donde guarde el archivo txt?
    He seguido todos los pasos y despues de Añadir no puedo recuperar esa informacion.

    Gracias

Leave a Reply

  • Buy Cheapest buy viagra from canada Now Best Prices. Order Cheap Meds Without Rx.
  • cialis next day Online Without Prescription Free Viagra Pills! Best Online.
  • Buy Cheap effects of viagra Online Pharmacy At The Best Price! Low Prices.
  • Buy Cheap viagra store in canada Now Cheap Prescription Drugs. Top Online Pharmacy.
  • Buy Cheap viagra cialis canadian pharmacy Now Best Drugstore. Drugs, Health And Beauty.
  • Buy Cheap viagra ads Now No Prescription Needed. WorldWide Shipping.
  • Buy Cheap order sublingual cialis Now Best Internet. Internet Prices For order sublingual cialis!
  • Buy Cheapest order Levitra Super Now Online Prices For order Levitra Super! Low Prices.
  • Buy Cheap best price viagra Online Pharmacy Store. 24/Online Pharmacy.
  • Buy Cheapest cialis precautions Now Best Online. Order Cheap Meds Without Rx.
  • Buy Cheap cialis soft gel india Now Drug Store Without A Prescription. Low Prices.
  • Buy Cheap canadian cialis Now WorldWide Shipping. Cheap Prescription Drugs.
  • Buy Cheap who has the cheapest cialis Now Internet Prices For who has the cheapest cialis! Best Online.
  • Buy Cheapest cialis from mexico Online No Prescription Needed. Low Prices.
  • Buy Cheapest viagra ad Online WorldWide Shipping. Pharmacy Store.
  • Buy Cheap recreational sex levitra Now Best Drugstore. Discount Pharmacy Online.
  • Buy Cheapest generic cialis Online Guaranteed Shipping. Free Viagra Pills!
  • Buy Cheapest buy sublingual viagra online Now Cheap Pharmacy Online. Best Internet.
  • Buy Cheap ciallis or viagra Now Buy Medications Online. WorldWide Shipping.
  • Buy Cheapest viagra amsterdam Now Cheap Prescription Drugs. Best Drugstore.
  • Buy Cheapest gernic viagra Online Internet Prices For gernic viagra! Best Online.
  • Buy Cheapest uk levitra Online Best Internet. Buy Medications Online.
  • Buy Cheap buy levitra on line Now Online Medical Shop. Online Prices For buy levitra on line!
  • Buy Cheapest tablet viagra Now We Can Offer You Visit Our Online Pharmacy.
  • Buy Cheap cialis women Now Drugs, Health And Beauty. Top Online Pharmacy.
  • Buy Cheap viagra and alternatives Online Best Drugstore. Internet Prices For viagra and alternatives!
  • Buy Cheap gel viagra Now WorldWide Shipping. Drugs, Health And Beauty.
  • Buy Cheap buy generic levitra Online Best Online. Buy Medications Online.
  • Buy Cheap buying cialis online Online 24/Internet)(safe Pharmacy. Best Prices.
  • Buy Cheap cialis buy Online Cheap Pharmacy Online. Top Online Pharmacy.
  • Buy Cheap bayer levitra online pharmacy cheapest Now Top Online Pharmacy Supplier. Best Drugstore.
  • Buy Cheapest cialis viagra packs Now Low Prices. Safe And Secure Payment System.
  • Buy Cheapest cialis levia and viagra Online Best Online. Online Medical Shop.
  • Buy Cheap order levitra Now Cheap Online Pharmacy. Guaranteed Shipping.
  • Buy Cheap dysfunction erectile levitra Online No Prescription Needed. Best Internet.
  • Buy Cheap maximize effects of levitra Online Guaranteed Shipping. Free Viagra Pills!
  • Buy Cheap approval cialis Online Best Online. The Largest Internet Pharmacy.
  • Get generic cheap cialis Without Prescription Consultation. 24/Online Pharmacy.
  • Buy Cheap side affects of viagra Now Online Medical Shop. Buy Medications Online.
  • Buy Cheap daily dose cialis availability Now Best Prices. Cheap Meds Without Prescription.
  • Buy Cheapest discount brand viagra Online 24/Online Pharmacy. Low Prices.
  • Buy Cheap best results for taking cialis Online Pharmacy Store. Special Prices For best results for taking cialis!
  • Buy Cheap cialis generique Now Guaranteed Shipping. No Prescription Needed.
  • Buy Cheapest levitra consultation Now Online Medical Shop. Guaranteed Shipping.
  • Buy Cheapest vardenafil safe levitra alternative Now Pharmacy Store. Internet Prices For vardenafil safe levitra alternative!
  • Buy Cheapest cialis online generic Online Cheap Prescription Drugs. Low Prices.
  • viagra online in canada Online Without Prescription Best Prices. WorldWide Shipping.
  • Buy Cheap generic online viagra Now Online Medical Shop. Discount Pharmacy Online.
  • Buy Cheap viagra effect on women Now Order Cheap Meds Without Rx. Best Internet.
  • Buy Cheap cialis where Now Best Internet. Pharmacy At The Best Price!
  • Buy Cheapest levitra result Now Pharmacy Store. Pharmacy At The Best Price!
  • Buy Cheap cialis canada prescription Online Cheap Online Pharmacy. WorldWide Shipping.
  • Buy Cheap order viagra online Now Top Online Pharmacy. 24/Online Pharmacy.
  • Buy Cheap drug for impotence levitra Online Pharmacy Store. Drugs, Health And Beauty.
  • Buy Cheapest female viagra sildenafil Online Best Prices. Cheap Prescription Drugs.
  • Buy Cheap method levitra Now No Prescription Needed. Cheap Online Pharmacy.
  • Buy Cheapest viagra cheapest Online Low Prices. Discount Pharmacy Online.
  • Buy Cheap women cialis Now 100% Satisfaction Guaranteed. Low Prices.
  • Buy Cheap cialis free shipping Online Pharmacy Store. Discount Online Pharmacy.
  • Buy Cheap discount cialis Now Free Viagra Pills! Pharmacy At The Best Price!
  • Buy Cheapest can woman take cialis Online 24/Online Pharmacy. Best Online.
  • Buy Cheapest levitra versus cialis Now Best Prices. 24/Internet)(safe Pharmacy.
  • Buy Cheapest levitra viagra cialis best Now Internet Prices For levitra viagra cialis best! Pharmacy Store.
  • Buy Cheap over the counter viagra Now Bonus Pills And Reorder Discounts! Low Prices.
  • sildenafil cialis generico Online Without Prescription Low Prices. Online Medical Shop.
  • Buy Cheap purchase cialis online Now Pharmacy Store. Order Cheap Meds Without Rx.
  • Buy Cheapest sample pak levitra Online Best Internet. Cheap Prescription Drugs.
  • Buy Cheap buy online cialis Online Top Online Pharmacy. Best Drugstore.
  • Buy Cheapest cialis levitra Online Best Drugstore. Guaranteed Shipping.
  • Buy Cheap soft viagra fast delivery Now 100% Satisfaction Guaranteed. Low Prices.
  • Buy Cheapest order 50mg viagra Now Pharmacy Store. Online Prices For order 50mg viagra!
  • experience with cialis Online Without Prescription Best Drugstore. Best Prices.
  • Buy Cheapest women take viagra Online Pharmacy At The Best Price! Low Prices.
  • Buy Cheap viagra effects Now Pharmacy At The Best Price! Best Internet.
  • Buy Cheapest viagra pennis enlargement Now Cheap Pharmacy Online. WorldWide Shipping.
  • Buy Cheap discount viagra generic Now Low Prices. All Medications Are Certificated!
  • Buy Cheap buy cheapest viagra online Now WorldWide Shipping. Guaranteed Shipping.
  • Buy Cheap best buy meridia phentermine propecia viagra Now The Largest Internet Pharmacy. Best Prices.
  • Buy Cheap generic cialis in stock Online Special Prices For generic cialis in stock! Best Internet.
  • Buy Cheap levitra sex pill Online Cheap Prescription Drugs. Best Drugstore.
  • Buy Cheap cialis for overseas Now Top Online Pharmacy. Discount Pharmacy Online.
  • Buy Cheapest cialis offers Online Cheap Prescription Drugs. Best Online.
  • Buy Cheapest non prescription type cialis Now Best Drugstore. Cheap Online Pharmacy.
  • Buy Cheapest erection viagra Now Best Drugstore. Internet Prices For erection viagra!
  • Buy Cheap cialis generic purchase Online Best Online. Order Cheap Meds Without Rx.
  • Buy Cheapest cialis in uae Now Best Prices. Buy Medications Online.
  • Buy Cheapest levitra sperm pills Online Best Online. Special Prices For levitra sperm pills!
  • Buy Cheapest order female viagra Online Pharmacy Store. Top Online Pharmacy.
  • Buy Cheap cialis vs cialis professional Online Pharmacy At The Best Price! Best Drugstore.
  • Buy Cheapest get viagra in canada Online Free Viagra Pills! Pharmacy Store.
  • levitra tabs Online Without Prescription Low Prices. Free Viagra Pills!
  • Buy Cheapest herbal womans viagra Now 24/Online Pharmacy. Free Viagra Pills!
  • Buy Cheapest cialis wholesale Now Discount Online Pharmacy. Best Prices.
  • Buy Cheapest buying online viagra Now Cheap Pharmacy Online. Best Drugstore.
  • Buy Cheap online ed drugs viagra samples package Now Cheap Online Pharmacy. Top Online Pharmacy.
  • Buy Cheap viagra cialis store Online Internet Prices For viagra cialis store! Best Internet.
  • Buy Cheap levitra half life Now Free Viagra Pills! Top Online Pharmacy.
  • Buy Cheap viagra plus cialis Now Top Online Pharmacy. Drugs, Health And Beauty.
  • Buy Cheap ordering viagra Now Best Prices. Special Prices For ordering viagra!
  • Buy Cheapest viagra cialis levitra comparison Online Best Prices. No Prescription Needed.