如何根据标签显示UIPickerView的选定值

时间:2014-01-14 13:49:22

标签: ios uipickerview uipickerviewcontroller

我试图根据视图中标签的值显示带有选定值的UIPickerView。

例如,如果标签值为2,当我打开pickerView时,我希望在选择器中选择值2。这会怎么样?

我的代码:

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{

  //res is array
  return [[res objectAtIndex:row]objectForKey:@"choice_name"];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    //choiceList is sting
    self.choiceList = [NSString stringWithFormat:@"<r_PM act='closepos_choice' cl_choice='%d'/>", row];
}

 - (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {

UILabel *pickerLabel = (UILabel *)view;
if (pickerLabel == nil) {
    CGRect frame = CGRectMake(0.0, 0.0, 300, 30);
    pickerLabel = [[[UILabel alloc] initWithFrame:frame] autorelease];
    [pickerLabel setTextAlignment:UITextAlignmentCenter];
    [pickerLabel setBackgroundColor:[UIColor clearColor]];
    [pickerLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:16.0]];

    //EDITED CODE FOR C_X
    NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
    [f setNumberStyle:NSNumberFormatterDecimalStyle];
    NSNumber * myNumber = [f numberFromString:lblOtomatikPozKap.text];
    [f release];

    NSInteger index = [res indexOfObject:myNumber];

    if(index != NSNotFound ){

        [self.pickerView selectRow:index inComponent:0 animated:NO];
    }

    //EDITED FOR AUSTIN
    NSInteger indexOfItem = [res indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
    return [[obj objectForKey:@"choice_name"] isEqualToString:@"2"];
    }];

    if (indexOfItem != NSNotFound)
    {
    [self.pickerView selectRow:indexOfItem inComponent:1 animated:NO];
    }
 }

NSString *str = [NSString stringWithFormat:@"%d- %@", row, [[res objectAtIndex:row]objectForKey:@"choice_name"]];

[pickerLabel setText:str];

return pickerLabel;
}

//Not working at all
- (void)selectRow:(UIPickerView*)row inComponent:(NSInteger)component animated:(BOOL)animated
{}

2 个答案:

答案 0 :(得分:1)

您可以在pickerview selectRow:inComponent:animated上调用此方法来选择一行: 修改

您正在从res获取字符串,首先您必须将标签字符串添加到此数组,以便在pickerView中包含此行。  之后在viewWillAppear或您想要调用此方法的任何其他方法。 首先获得该sring / object的索引。

NSInteger index=[resindexOfObject:label.text];

现在选择行。

if(index != NSNotFound ){
 [self.myPicker selectRow:index inComponent:0 animated:NO]
}

答案 1 :(得分:1)

首先,您将获得要从数据源中选择的值的索引(在本例中为res数组)。然后,在显示选择器之前,您可以调用selectRow:inComponent:animated:

NSInteger indexOfItem = [res indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
    return [[obj objectForKey:@"choice_name"] isEqualToString:@"2"];
}];

if (indexOfItem != NSNotFound)
{
    [self.pickerView selectRow:indexOfItem inComponent:1 animated:NO];
}

// Show picker here