2

我正在尝试根据视图中标签的值显示具有选定值的 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
{}
4

2 回答 2

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
于 2014-01-14T14:21:04.200 回答
1

您可以通过调用此方法来选择一行pickerview selectRow:inComponent:animated编辑:

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

NSInteger index=[resindexOfObject:label.text];

现在选择行。

if(index != NSNotFound ){
 [self.myPicker selectRow:index inComponent:0 animated:NO]
}
于 2014-01-14T14:05:14.410 回答