UIPickerView da NSDictionary

Mattepuffo's logo
UIPickerView da NSDictionary

UIPickerView da NSDictionary

Nel precedente articolo su Obj-C avevo analizzato come usare le UIPickerView.

In quel caso abbiamo usato un semplice NSArray.

Non che sia sbagliato, ma nel caso specifico ho la necessità di rendere il componente più simile a una <select> HTML, dove il valore reale non è uguale a quello visualizzato.

Per ottenere questo comportamento dobbiamo impostare come sorgente dati non un NSArray, ma un NSDictionary.

Quindi nel file .h:

#import <UIKit/UIKit.h>

@interface ControllerAziendaReg : UIViewController {    
    NSDictionary *dictionaryForma;
    NSArray *keysForma;
    NSArray *objectsForma;
    UIActionSheet *sheetForma;
}

@property (retain, nonatomic) IBOutlet UIPickerView *pickerForma;

@end

Un oggetto di tipo NSDictionary è composto di due parti: una chiave alla quale corrisponde un valore.

Queste due componenti le comporremo attrverso due NSArray.

 

Nel file .m:

- (void)viewDidLoad
{
    [super viewDidLoad];    
    keysForma = [NSArray arrayWithObjects:@"1", @"2", nil];
    objectsForma = [NSArray arrayWithObjects:@"3", @"4", nil];
    dictionaryForma = [NSDictionary dictionaryWithObjects:objectsForma forKeys:keysForma];
}
............
#pragma mark PickerForma
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    return [dictionaryForma objectForKey:[keysForma objectAtIndex:row]];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return [keysForma count];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Attenzione" message:[keysForma objectAtIndex:row] delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
    [alert show];
}

Come vedete nel metodo viewDidLoad componiamo i due NSArray e li impostiamo come chiavi / valori nell'NSDictionary attraverso il metodo dictionarywithObject:forKeys.

Provate a vedere come cambia il valore dell'alert nel metodo didSelectRow se usate un NSArray piuttosto che l'altro.


Condividi

1 Commenti

  • Angelo

    Ciao, il tuo tutorial è propio quello di cui avevo bisogno, ma al posto di creare una allert, vorrei leggere il valore del picker. Ho provato così:<br /><br />-(void) pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {<br /> [numeroSelezionato setText:[NSString stringWithFormat:@" %@",[keysForma objectAtIndex:row]]];<br /><br />Ma non mi funziona.

    01/12/2012

Commentami!