Mattog1456
Mattog1456

Reputation: 61

UIPickerView data

I have a uipickerview which is used to displays names in a uitextfield, any ideas on how I would pass a value that is hidden from the user into a variable. Can I somehow associate the value with the name in the NSArray while not displaying it. Thank you

Trying a dictionary but am stuck on something that is probably pretty simple, I have a dictionary

    NSArray *keys = [NSArray arrayWithObjects:@"1", @"2", nil];
NSArray *objects = [NSArray arrayWithObjects:@"3", @"4", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

and in didSelectRow I have

    NSString *itemKey = [NSString stringWithFormat:@"%f", row];
    survonemd.text = [dictionary objectForKey:itemKey];

which seems ok

but am stuck on titleForRow

any help or tips would be much appreciated.

I now have -

@property (nonatomic, retain) NSArray *keys;
@property (nonatomic, retain) NSArray *objects;


@synthesize keys;
@synthesize objects;


self.keys = [NSArray arrayWithObjects:@"1", @"2", @"3", nil];
self.objects = [NSArray arrayWithObjects:@"4", @"5", @"6", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
NSString *itemKey = [keys objectAtIndex:row];
return [dictionary objectForKey:itemKey]; 
}

- (void) pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
NSString *itemKey = [keys objectAtIndex:row];
survonemd.text = [dictionary objectForKey:itemKey]; 
}

It runs and the picker view gets called from the textfield but no data is displayed in the picker. Please help.

Upvotes: 1

Views: 3012

Answers (1)

user467105
user467105

Reputation:

Instead of generating the key string from the row number (for which you would use %i instead of %f by the way), use the row as the index into the keys array:

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    NSString *itemKey = [keys objectAtIndex:row];
    survonemd.text = [dictionary objectForKey:itemKey]; 
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSString *itemKey = [keys objectAtIndex:row];
    return [dictionary objectForKey:itemKey];   
}

This way, the key values also don't have to be numbers-as-strings.

Define your keys and dictionary objects as properties and set them using self.keys = ... so you can access them properly.

Upvotes: 1

Related Questions