我需要在选择表格单元格时添加一个新单元格。新单元格应位于所选单元格下方。我们能做到吗?
下面是我创建 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 方法:
- (void)insertRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation
这将调用
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
TableView 数据源的方法,并使用您选择的动画更新您的表。
您不会像在发布的代码中那样在 didSelectRowAtIndexPath 方法中创建新单元格。
编辑以添加信息。
要设置 indexPaths 数组(针对您的情况),您可以这样做:
NSInteger row = [indexPath row];
NSInteger section = [indexPath section];
NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:row+1 inSection:section];
NSArray *indexPaths = [NSArray arrayWithObject:indexPath];
关于ios - 我们如何在 TableView 中的两个给定单元格之间动态添加新单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10564087/