[英]Add a subview to a UITableView cell's view
我试图在选择该单元格时将一个子视图(包含一个UIDatePicker)添加到UITableView单元格的视图中。 但是,当我选择该单元格时,不会显示子视图的内容。
下面是检查用户是否选择了要将子视图添加到的单元格的地方:
- (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];
}
另外,下面是我创建日期选择器并显示它的方法:
- (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");
}
下面是如何将所选行设置为显示日期选择器所需的高度:
- (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;
}
我想您缺少UIDatePicker的框架。 您需要使用frame进行初始化。或者是否在代码中将frame设置为其他位置。
- (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];
}
将视图添加到UITableViewCell将不起作用。 而是将它们添加到UITableViewCell的contentView中。
就是说,在didSelectRowAtIndexPath中添加视图并不是一件好事。 如果我两次选择该行会怎样? 如果我滚动以使该行不再可见(会重复使用该单元格,并且仍附加了日期选择器),将会发生什么情况。您至少需要适当地处理prepareForReuse。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.