Reputation: 3221
I'm attempting to add a subview (which contains a UIDatePicker) to the view of a UITableView cell when that cell is selected. However, when I select that cell, the content of the subview is not being displayed.
Below is where I check to see if the user selects the cell that I want to add the subview to:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == SectionOne && indexPath.row == RowOne && self.datePickerIsShowing == NO){
[self.RowOne addSubview:_datePicker];
[self showDatePickerCell];
} else{
[self hideDatePickerCell];
}
[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}
Additionally, below is how I create the date picker and show it:
- (void)createDatePicker{
_datePicker = [[UIDatePicker alloc]initWithFrame:CGRectMake(0, 0, 100, 20)];
_datePicker.datePickerMode = UIDatePickerModeTime;
_datePicker.clipsToBounds = YES;
_datePicker.backgroundColor = [UIColor colorWithRed:0.922 green:0.937 blue:0.949 alpha:1];
}
- (void)showDatePickerCell {
self.datePickerIsShowing = YES;
self.datePicker.hidden = NO;
[self.tableView reloadData];
NSLog(@"Show date picker");
}
And below is how I set the selected row to be the required height to show the date picker:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
CGFloat rowHeight = self.tableView.rowHeight;
if (indexPath.section == SectionOne && indexPath.row == RowOne && self.datePickerIsShowing == YES){
rowHeight = kDatePickerCellHeight;
}
else{
rowHeight = self.tableView.rowHeight;
}
return rowHeight;
}
Upvotes: 0
Views: 1606
Reputation: 2041
I guess you are missing the frame for UIDatePicker. You need to initialize with frame.Or Have you set the frame other place in your code.
- (void)createDatePicker{
_datePicker = [[UIDatePicker alloc]initWithFrame:CGRect(0,0,100,20)];
_datePicker.datePickerMode = UIDatePickerModeTime;
_datePicker.clipsToBounds = YES;
_datePicker.backgroundColor = [UIColor colorWithRed:0.922 green:0.937 blue:0.949 alpha:1];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell =[UITableViewCell cellForItemAtIndexPath:indexPath];
if (indexPath.section == SectionOne && indexPath.row == RowOne && self.datePickerIsShowing == NO){
[cell addSubview:_datePicker];
[self showDatePickerCell];
} else{
[self hideDatePickerCell];
}
[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}
Upvotes: 2
Reputation: 32622
Adding views to a UITableViewCell won't work. Add them to the UITableViewCell's contentView instead.
That said, adding views in didSelectRowAtIndexPath is not really a good thing to do. What happens if I select the row twice? What happens if I scroll so that row is no longer visible (the cell will be reused, still with datepicker attached. You'll need to handle prepareForReuse properly at a minimum.
Upvotes: 0