iosuitableviewuidatepickernstableviewcell

Adding UIDatePicker to cell content view


I'm attempting to put an instance of UIDatePicker in the accessory view of a UITableView cell, and have been following this SO thread as a template. However, it looks as if the picker is being placed above the cell entirely:

enter image description here

Below is the code I'm using to try to add a Date Picker to the accessory view of a UITableView:

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

    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    }

    cell.backgroundColor = [UIColor colorWithRed:0.922 green:0.937 blue:0.949 alpha:1];

    switch (indexPath.row) {

        case EmployeeOvertimeRow:
            cell.textLabel.text = NSLocalizedString(@"Test", @"One");
            _datePicker = [[UIDatePicker alloc]init];
            _datePicker.datePickerMode = UIDatePickerModeTime;
            //OLD: cell.accessoryView     = _datePicker;
            //POST EDIT
            [cell.contentView addSubview:_datePicker];

            break;
        default:
            break;
    }

    return cell;
}

Does anyone have any guidance on what I'm doing wrong or how to fix this?


Solution

  • The accessoryView of a UITableViewCell is surely not what you think : it's the little view at the right of the cell, typically, it's an arrow, and it's pretty small, not made to be the width of the screen at all. You should try adding your view to the contentView. You will need to set a bigger height for your cell in the heightForRowAtIndexPath method, too.