Как я могу представить окно выбора так же, как это делает клавиатура?

Я хочу, чтобы UIPickerView отображался, когда я нажимаю кнопку (как на клавиатуре), а затем исчезал, когда пользователь касался любого места на экране. Как я могу это сделать? Спасибо.

Еще немного предыстории: у меня есть UITextField, который называется месяцами в UITableViewCell. Теперь лучший вариант для меня - поместить туда UIPikcerView, и пользователю будет проще просто выбрать месяц, а не вводить его (и это лучший способ). Но UIPickerView выглядит очень уродливо в UITableViewCell, не говоря уже о том, что я не могу изменить его гигантский размер. Так что мне делать в этом случае?


person sumderungHAY    schedule 07.06.2011    source источник
comment
Ваш заголовок не очень информативен. Пожалуйста, предоставьте более подробную информацию о том, чего вы пытаетесь достичь (в заголовке)   -  person Julian    schedule 07.06.2011
comment
Извини за это. Название было обновлено кем-то другим, но теперь я также предоставил больше информации по этому вопросу.   -  person sumderungHAY    schedule 07.06.2011


Ответы (2)


Вот как вы должны использовать UIPickerView для текстового поля в UITableView.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
    cell.selectionStyle= UITableViewCellSelectionStyleNone;
    UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(110, 10, 185, 30)];
    textField.clearsOnBeginEditing = NO;
    textField.textAlignment = UITextAlignmentRight;
    textField.delegate = self;
    [cell.contentView addSubview:textField];
    //textField.returnKeyType = UIReturnKeyDone;
    cell.textLabel.backgroundColor = [UIColor clearColor];
    cell.detailTextLabel.backgroundColor = [UIColor clearColor];

        // if you want a UIPickerView for first row... then do the following //
        // Here.. packSizePickerView is an object of UIPickerView

   if (indexPath.row == 1)
  {
    textField.tag=0;
    textField.delegate= self;
    packSizePickerView.delegate = self;
    packSizePickerView = [[UIPickerView alloc] init];
    packSizePickerView.autoresizingMask=UIViewAutoresizingFlexibleWidth;
    packSizePickerView.showsSelectionIndicator=YES;
    textField.inputView  = packSizePickerView;
    }

    // if you want to select date / months  in row 2, go for UIDatePickerView //

    if (indexPath.row == 1)
    {
        textField.tag = 1;
        UIDatePicker *datePicker = [[UIDatePicker alloc] init];
        datePicker.datePickerMode = UIDatePickerModeDate;
       [datePicker addTarget:self action:@selector(datePickerValueChangedd:) forControlEvents:UIControlEventValueChanged];
        datePicker.tag = indexPath.row;
        textField.delegate= self;
        textField.inputView = datePicker;
        [datePicker release];

    }

}

// Configure the cell...

NSInteger row = [indexPath row];
cell.textLabel.text = [myArray objectAtIndex:row];

return cell;

}

И для datePickerValueChangedd

- (void)datePickerValueChangedd:(UIDatePicker*) datePicker{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 50, 68, 68)];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateStyle = NSDateFormatterMediumStyle;
label.text = [NSString stringWithFormat:@"%@",[df stringFromDate:datePicker.date]];

    NSLog(@"I am inside the datePickerValueChanged   - - %@", label.text);
[df release];
    globalValue1 = label.text;

   // use a global variable to copy the value from the pickerView. //
   }    

Теперь в textFieldDidEndEditing:

-(void) textFieldDidEndEditing:(UITextField *)textField {
if (textField.tag ==0)
   [textField setText: globalValue0];

if (textField.tag ==1)
   [textField setText: globalValue1];

}

И чтобы отказаться от UIDatePicker, установите UIView как UIControl и

resignFirstResponder
person Legolas    schedule 07.06.2011
comment
Отличный ответ!! Это именно то, что я искал!! +1 - person Garoal; 02.08.2012

Я думаю, что вам нужно поместить свой UIPickerView «вне» видимого экрана и анимировать его при нажатии кнопки. Я не совсем уверен, как лучше всего от этого избавиться, но вы, вероятно, могли бы прослушать нажатие на родительском представлении, когда средство выбора видно, а затем анимировать его обратно.

person Julian    schedule 07.06.2011