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 に答える