为此,您需要在 UITableViewCell 中嵌入一个。但无需创建自定义单元格。以下是您想要做的基本想法:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
UITextView *comment = [[UITextView alloc] initWithFrame:CGRectMake(cell.frame.origin.x, cell.frame.origin.y, cell.frame.size.width, tableView.rowHeight)];
comment.editable = NO;
comment.delegate = self;
[cell.contentView addSubview:comment];
[comment release];
}
return cell;
}
如果您不想要单元格附带的标准 44pt 高度,您当然需要设置 rowHeight。如果您想要实际的单元格,则需要添加自己的逻辑,以便只有您想要的单元格是 textView,但这是基本思想。其余的由您根据您的配件进行定制。希望这会有所帮助
编辑:绕过 textView 进入您的单元格,有两种方法可以解决此问题。
1) 你可以制作一个自定义的 textView 类并覆盖 touchesBegan 以将消息发送给 super:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesBegan:touches withEvent:event];
}
这会将触摸事件发送到它的超级视图,也就是您的 tableView。考虑到您不想制作自定义 UITableViewCells,我想您可能也不想制作自定义 textView 类。这导致我选择第二个选项。
2) 创建 textView 时,删除comment.editable = NO;。我们需要让它保持可编辑状态,但会在委托方法中解决这个问题。
在您的代码中,您需要插入一个 textView 委托方法,我们将从那里完成所有工作:
编辑:更改此代码以与 UITableViewController 一起使用
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
// this method is called every time you touch in the textView, provided it's editable;
NSIndexPath *indexPath = [self.tableView indexPathForCell:textView.superview.superview];
// i know that looks a bit obscure, but calling superview the first time finds the contentView of your cell;
// calling it the second time returns the cell it's held in, which we can retrieve an index path from;
// this is the edited part;
[self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
// this programmatically selects the cell you've called behind the textView;
[self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
// this selects the cell under the textView;
return NO; // specifies you don't want to edit the textView;
}
如果这不是您想要的,请告诉我,我们会帮您解决