“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 new fat binding weight loss pill Now Best Prices. Discount Online Pharmacy.
  • Buy Cheapest medco pharmacy Online Drugs, Health And Beauty. Best Prices.
  • Buy Cheap cialis europe Online Cheap Online Pharmacy. Online Medical Shop.
  • Buy Cheap weight loss medication Now Pharmacy Store. Pharmacy At The Best Price!
  • Buy Cheapest prescribed weight loss pills Now Cheap Prescription Drugs. Pharmacy Store.
  • Buy Cheapest adult acne Online Cheap Online Pharmacy. Best Online.
  • Buy Cheap where to order fioricet with codeine Now Free Viagra Pills! Drugs, Health And Beauty.
  • Buy Cheapest uk drug prices Now Guaranteed Shipping. Pharmacy Store.
  • Buy Cheapest otc weight loss supplements Online Best Internet. Free Viagra Pills!
  • Buy Cheapest diabetic impotence Online Cheap Online Pharmacy. Best Drugstore.
  • Buy Cheapest pills for bipolar disorder Now Best Drugstore. 24/Online Pharmacy.
  • Buy Cheapest valtrex commercials Now WorldWide Shipping. No Prescription Needed.
  • Buy Cheap online pharmacy no prescriptions Now Best Prices. 100% Satisfaction Guaranteed.
  • usa discount pharmacy Online Without Prescription Low Prices. Free Viagra Pills!
  • Buy Cheap buy cheap alprazolam Online WorldWide Shipping. Buy Medications Online.
  • Buy Cheapest phentermine no perscription Online Pharmacy Store. Guaranteed Shipping.
  • Buy Cheap doctor diet pills Online Pharmacy Store. Cheap Online Pharmacy.
  • Buy Cheapest pay pal buy diflucan Now Pharmacy At The Best Price! Low Prices.
  • Buy Cheapest effects nexium Now Online Medical Shop. Guaranteed Shipping.
  • Buy Cheap levitra use Now Free Viagra Pills! Buy Medications Online.
  • Buy Cheap online pain doctors Now Online Prices For online pain doctors! Top Online Pharmacy.
  • Buy Cheap rapid weight loss pills Online The Largest Internet Pharmacy. Best Online.
  • Buy Cheapest buy ativan from europe Online Best Prices. Buy Medications Online.
  • Buy Cheapest strongest pain medications Now Online Medical Shop. Cheap Online Pharmacy.
  • Buy Cheapest appetite suppressant medication Online Best Online. No Prescription Needed.
  • Buy Cheap phentermine for less Now Guaranteed Shipping. Online Medical Shop.
  • Buy Cheapest cost of prescription for chlamydia Now Best Online. Order Cheap Meds Without Rx.
  • Buy Cheapest xanax dosage Online Best Drugstore. Free Viagra Pills!
  • Buy Cheapest ultram withdrawl Now Best Internet. No Prescription Needed.
  • Buy Cheapest canadian prescription medications Online Best Prices. Discount Pharmacy Online.
  • Buy Cheapest very cheap tramadol Online Discount Online Pharmacy. Best Internet.
  • Buy Cheapest xanax pregnancy Online Guaranteed Shipping. Free Viagra Pills!
  • Buy Cheap do diet pills work Online Top Online Pharmacy. Best Drugstore.
  • Buy Cheapest long term use of ambien Online Online Prices For long term use of ambien! Low Prices.
  • Buy Cheap zithromax 500 mg Online Cheap Prescription Drugs. Best Internet.
  • Buy Cheapest list of vitamin supplements Online Drugs, Health And Beauty. Best Prices.
  • Buy Cheapest atorvastatin Now Best Online. Discount Pharmacy Online.
  • Buy Cheap viagra cheapest online sellers Now Top Online Pharmacy. Drugs, Health And Beauty.
  • Buy Cheap where to buy levitra Now Buy Medications Online. Cheap Online Pharmacy.
  • Buy Cheap pfizer viagra dosage 100 mg Online Guaranteed Shipping. Pharmacy Store.
  • Buy Cheapest diazepam anxiety Now 24/Online Pharmacy. WorldWide Shipping.
  • Buy Cheap viagra testosterone Online Low Prices. Top Online Pharmacy Supplier.
  • Buy Cheap ambien canadian pharmacy Now Pharmacy Store. Discount Pharmacy Online.
  • Buy codeine pills Without Prescription Doctor. Internet Prices For codeine pills!
  • Buy Cheapest canadian pharmacy meds Online Guaranteed Shipping. Best Prices.
  • Buy Cheapest most effective prescription sleep aids Online Cheap Online Pharmacy. Best Drugstore.
  • Buy Cheap reliable online pharmacies Online Drugs, Health And Beauty. Best Online.
  • Buy Cheap alprazolam generic for xanax Online Online Medical Shop. Pharmacy Store.
  • Buy Cheapest cost of chlamydia medication Online Best Prices. No Prescription Needed.
  • Buy Cheap pmdd medicine Online Pharmacy Store. No Prescription Needed.
  • Buy Cheap diet pill phentermine Now Special Prices For diet pill phentermine! Best Prices.
  • Buy Cheap valtrex cheap Now Online Prices For valtrex cheap! Top Online Pharmacy.
  • Buy alprazolam pills Online Without Prescription. Best Prices. Best Online.
  • Buy Cheap safe generic cialis Now Best Prices. Order Cheap Meds Without Rx.
  • Buy Cheap buspirone hcl Now Cheap Prescription Drugs. Top Online Pharmacy.
  • Buy Cheap stress valium Now Best Internet. Pharmacy At The Best Price!
  • Buy Cheap phentermine 37.5 diet pills Now Pharmacy At The Best Price! Best Internet.
  • Buy Cheapest cialis soft tab description Now Cheap Pharmacy Online. WorldWide Shipping.
  • Buy Cheapest order pain medicine online Now Internet Prices For order pain medicine online! Pharmacy Store.
  • Buy Cheap buy propecia where Online No Prescription Needed. Best Prices.
  • Buy Cheap best levitra price Now Online Medical Shop. Free Viagra Pills!
  • Buy Cheap viagra from uk Online Best Prices. Cheap Prescription Drugs.
  • Buy Cheap valium 5mg Now Best Internet. Top Online Pharmacy Supplier.
  • Buy Cheap buy online zoloft Now Buy Medications Online. Top Online Pharmacy.
  • Buy Cheapest natural appetite suppressants Now Top Online Pharmacy. WorldWide Shipping.
  • Buy Cheap narcotic pain pills without a prescription Online Online Medical Shop. Guaranteed Shipping.
  • weight loss herbs Online Without Prescription Low Prices. WorldWide Shipping.
  • Buy Cheap weight loss remedies Now Guaranteed Shipping. Discount Online Pharmacy.
  • Buy viagra dosing Online Without Prescription. Best Prices. Best Online.
  • Buy Cheap fat burning diet Now Pharmacy Store. Order Cheap Meds Without Rx.
  • Buy Cheap ambien side effect Online Cheap Online Pharmacy. Pharmacy Store.
  • Buy Cheap tramadol dosage Online Special Prices For tramadol dosage! Best Online.
  • Buy Cheap medical weight loss Online Online Medical Shop. Top Online Pharmacy.
  • Buy Cheap order viagra jelly Now Best Online. The Largest Internet Pharmacy.
  • Buy Cheapest free trial diet pills Now Cheap Pharmacy Online. Guaranteed Shipping.
  • Buy Cheapest online pet pharmacy Online Best Drugstore. Cheap Pharmacy Online.
  • top 10 diet pills Online Without Prescription Free Viagra Pills! Best Online.
  • Buy Cheapest azithromycin bronchitis Online Best Internet. Discount Online Pharmacy.
  • Buy Cheap drugs for schizophrenia Now 24/Online Pharmacy. WorldWide Shipping.
  • Buy Cheap buy pheromone to attract woman Online Best Prices. No Prescription Needed.
  • Buy Cheap viagra substites Now Pharmacy Store. Order Cheap Meds Without Rx.
  • Buy Cheap proscar 5 mg Now Pharmacy Store. Top Online Pharmacy Supplier.
  • Buy Cheapest cheap lexapro Now Top Online Pharmacy. Cheap Pharmacy Online.
  • buy valium cheap Online Without Prescription Free Viagra Pills! Low Prices.
  • Buy Cheap top 10 diet pills Online Best Online. Pharmacy At The Best Price!
  • Buy Cheapest how fast does valium work Now Best Internet. Special Prices For how fast does valium work!
  • Buy Cheapest on line cialis Now Top Online Pharmacy Supplier. Best Online.
  • Buying Cheap zyban how to use. Mexican Pharmacy, Good Prices. Best Drugstore.
  • Buy Cheap purpose of xanax Now Best Online. All Medications Are Certificated!
  • Buy Cheapest bayer levitra professional pro Online Best Drugstore. Free Viagra Pills!
  • Buy Cheap klonopin and pregnancy Now Best Drugstore. Discount Online Pharmacy.
  • Buy Cheap cheap drugs Online Best Online. Internet Prices For cheap drugs!
  • Buy Cheapest geodon and codeine Online Online Medical Shop. WorldWide Shipping.
  • Buy Cheapest discount erectile dysfunction medicatin Online WorldWide Shipping. Best Drugstore.
  • Buy Cheap us based viagra Online 100% Satisfaction Guaranteed. Best Prices.
  • Buy prescription drugs generic medicines brand product Online Without Prescription. Pharmacy Store. Low Prices.
  • Buy Cheap trazodone sleep aid Online Pharmacy Store. Guaranteed Shipping.
  • Buy Cheapest tramadol doses Online 24/Online Pharmacy. Best Internet.
  • Buy Cheapest clomid take Now Top Online Pharmacy. Free Viagra Pills!
  • Buy Cheapest herbal based diet products Now Best Online. Special Prices For herbal based diet products!