UITableView con índices

Share


En el ejemplo de hoy nos hemos basado en el tercer caso práctico de TableViewSuite de iPhone Dev Center. (Podéis descargarlo en http://developer.apple.com/iphone/library/samplecode/

TableViewSuite/index.html )

UITableView, es una de las clases más utilizadas, pues nos permite mostrar información en forma de lista y puede ser ordenada, agrupada y localizada de forma sencilla.

En el ejemplo de hoy, vamos a mostrar una sencilla lista de zonas horarias, ordenadas por orden alfabético, con la primera letra de cada región como cabecera de la sección y con un índice para acceder de forma rápida.

Para obtener la información de las zonas horarias, en nuestra clase delegada de UIApplication, obtenemos dicha información mediante la clase abstracta NSTimeZone, a través de su propiedad knownTimeZoneNames en una variable de tipo NSArray aunque en nuestro caso preferimos hacerlo con una del tipo NSMutableArray (hereda de NSArray y por lo tanto implementa operaciones básicas de inserción y eliminación de elementos en la lista).

C++:
  1. NSMutableArray* nuestravariable = [NSTimeZone knownTimeZoneNames];

Hemos preferido NSMutableArray ya que está indicada para el manejo personalizado de la lista, y al ser una subclase de NSArray nos permitirá implementar métodos como:

C++:
  1. insertObject:atIndex:
  2. removeObjectAtIndex:
  3. addObject:
  4. removeLastObject
  5. replaceObjectAtIndex:withObject:

En nuestra clase controladora, heredaremos de UITableViewController para manejar nuestro TableView. Aprovecharemos su método initWithStyle para aplicar un estilo a nuestro TableView (ya visto en nuestra clase delegada de UIApplication con initWithStyle:UITableViewStylePlain). Podéis probar con el estilo UITableViewStyleGrouped y comprobar vosotros mismo el cambio.

-Métodos de UITableViewDataSource
En nuestra clase controladora vamos a sobreescribir algunos métodos necesarios para el correcto funcionamiento de la aplicación. En concreto son de la clase UITableViewDataSource que son llamados a partir del objeto UITableView por medio de eventos.

1. numberOfSectionsInTableView

Método opcional de la clase UITableViewDataSource, que será llamado en el momento que hayamos insertado todos los datos, si nos fijamos en la pila de llamadas a través de:

Como no hay mejor manera de aprender, que comprobar por nosotros mismos ciertos comportamientos, en lugar de devolver el número de secciones de nuestro TableView, pongamos un 2 (return 2;).

2. numberOfRowsInSection

Al igual que el método anterior, a través de UITableViewDataSource, devolvemos el número de regiones de cada sección, el cual es llamado desde:

3. titleForHeaderInSection

Pregunta al DataSource por el título de la cabecera de la sección especificada.

4. sectionIndexTitlesForTableView

Pregunta al DataSource para que devuelva los títulos para las secciones del TableView.

5. sectionForSectionIndexTitle

Pregunta al DataSource para devolver el índice de una sección.

* Si obviamos estos tres últimos métodos, veremos como los datos aparecen de forma plana, sin cabeceras ni índices. Es conveniente comentar cada uno de ellos para ver el resultado y comprender mejor el ejemplo.

-Métodos de UITableView

1. cellForRowAtIndexPath

Devuelve el valor de una determinada fila o celda a partir de un índice.

Para finalizar, una de las funciones más importantes en nuestro ejemplo de hoy es la encargada de rellenar la información que será mostrada. Para ello, mediante un objeto diccionario de la clase NSMutableDictionary nos dispondremos a rellenarlo.

C++:
  1. NSMutableDictionary *indexedTimeZones = [[NSMutableDictionary alloc] init]; for (NSString *name in knownTimeZoneNames)
  2.  
  3. {
  4.  
  5. // The region name is unused in this example
  6.  
  7. NSArray *components = [name componentsSeparatedByString:@"/"];
  8.  
  9. NSString *timeZoneLocaleName = localeNameForTimeZoneNameComponents(components);
  10.  
  11. NSString *firstLetter = [timeZoneLocaleName substringToIndex:1];
  12.  
  13. NSMutableArray *indexArray = [indexedTimeZones objectForKey:firstLetter];
  14.  
  15. if (indexArray == nil)
  16.  
  17. {
  18.  
  19. indexArray = [[NSMutableArray alloc] init];
  20.  
  21. [indexedTimeZones setObject:indexArray forKey:firstLetter];
  22.  
  23. [indexArray release];
  24.  
  25. }
  26.  
  27. NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:name];
  28.  
  29. NSDictionary *timeZoneDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:timeZone, @"timeZone",    timeZoneLocaleName, @"timeZoneLocaleName", nil];
  30.  
  31. [indexArray addObject:timeZoneDictionary];
  32.  
  33. }

El diccionario indexedTimeZones irá rellenando cada una de las letras de las regiones en una variable CFString y en otro diccionario hijo (timeZoneDictionary) las zonas horarias que empiezen por esa letra. A continuación se ordenará el primer diccionario y por cada una de las letras se ordenarán igualmente los diccionarios que contienen (sortUsingDescriptors:sortDescriptors).

Nota: Interesante detalle el de mostrar una imagen nada más iniciar la aplicación, dado que nos lleva un tiempo el cargar la información de las zonas horarias. La imagen es una captura de la propia aplicación, así de esa manera, evitamos un desagradable efecto.

banner ad

One Response to “UITableView con índices”

  1. [...] iPhone Software wrote an interesting post today on UITableView con índicesHere’s a quick excerptEn el ejemplo de hoy nos hemos basado en el tercer caso práctico de TableViewSuite de iPhone Dev Center…. [...]

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!