当选中表格单元格时,我需要添加一个新的单元格。新单元格应该位于所选单元格下方。我们可以这样做吗?
以下是我创建4个单元格并想在第2个和第3个之间插入一个单元格的代码。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
cell= [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
if(indexPath.row == 0){
cell.textLabel.text = @"My Tweets";
cell.textLabel.textColor = [UIColor whiteColor];
cell.backgroundColor = [UIColor blackColor];
cell.imageView.image = [UIImage imageNamed:@"tweets.png"];
}
if(indexPath.row == 1){
cell.textLabel.text = @"Search";
cell.backgroundColor = [UIColor blackColor];
cell.textLabel.textColor = [UIColor whiteColor];
cell.imageView.image = [UIImage imageNamed:@"search.png"];
}
if(indexPath.row == 2){
cell.textLabel.text = @"Followers";
cell.textLabel.textColor = [UIColor whiteColor];
cell.backgroundColor = [UIColor blackColor];
cell.imageView.image = [UIImage imageNamed:@"followers.png"];
}
if(indexPath.row == 3){
cell.textLabel.text = @"Following";
cell.textLabel.textColor = [UIColor whiteColor];
cell.backgroundColor = [UIColor blackColor];
cell.imageView.image = [UIImage imageNamed:@"following.png"];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//here I have to insert a new cell below on the click this existing cell.
if(indexPath.row == 1)
{
NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:indexPath.row+1 inSection:0];
NSArray *indexPaths = [NSArray arrayWithObject:newIndexPath];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPaths] withRowAnimation:UITableViewRowAnimationAutomatic];
}
}
UITableView
的-beginUpdates
、-endUpdates
和-insertRowsAtIndexPaths:withRowAnimation:
方法。 - Christian Schnorr