将 UIPickerView 中的选定第二个组件设置为 NSString

Set Selected Second component in UIPickerView to a NSString

我有一个 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 的方式,因为它给了我一个错误。

你可能想要:

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 是如何分配的。不需要浪费分配和浪费数组复制。