将UIPickerView中的Selected Second组件设置为NSString

时间:2015-01-23 19:24:59

标签: ios objective-c nsdictionary uipickerview

我有NSDictionary个数组和字符串。然后,我有一个UIPickerView,其中包含2个从字典中获取数据的组件。第一个组件是一个字符串(来自字典),第二个组件是一个数组(来自同一个字典)。

didSelectRow方法中,我成功地将第一个组件项传递给字符串。我遇到的问题是将第二个组件选定对象设置为字符串。

这是我的代码:

- (void)viewDidLoad {
    values = [[NSDictionary alloc] initWithObjectsAndKeys:
                                     array1, @"key one",
                                     array2, @"key two", nil];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    NSMutableArray *tempArray = [[NSMutableArray alloc] init];
    if (component == 0)
    {
        rowSelection1 = [sortedValue objectAtIndex:row];

        for (id key in values) {
            if ([key isEqualToString:rowSelection1]) {
                [tempArray addObjectsFromArray:[values valueForKey:key]];
            }
        }

        secondComponent = [[NSMutableArray alloc] init];
        [secondComponent addObjectsFromArray:tempArray];
        [self.pickerView reloadAllComponents];
    }
    else
    {
        rowSelection2 = [tempArray objecAtIndex:row];
        NSLog(@"%@", rowSelection2);
    }
}

我唯一遇到麻烦的部分是在else语句中。我确定我不应该如何设置rowSelection2,因为它给了我一个错误。

1 个答案:

答案 0 :(得分:0)

你可能想要:

rowSelection2 = [secondComponent objectAtIndex:row];

因为它是您的secondComponent数组,其中包含选择器视图的第二个组件的当前内容。

这假定您使用secondComponent ivar填充第二个选择器组件。

您还有其他一些问题。将方法更改为:

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (component == 0) {
        rowSelection1 = sortedValue[row];

        NSMutableArray *tempArray = [[NSMutableArray alloc] init];
        for (id key in values) {
            if ([key isEqualToString:rowSelection1]) {
                [tempArray addObjectsFromArray:values[key]];
            }
        }

        secondComponent = tmpArray;

        [self.pickerView reloadComponent:1];
    } else {
        rowSelection2 = secondComponent[row];
        NSLog(@"%@", rowSelection2);
    }
}

注意使用现代数组和字典访问。请注意,无需重新加载所有组件,只需要重新加载。请注意secondComponent的分配方式。不需要浪费的分配和浪费的数组副本。