ios - 我们如何在 TableView 中的两个给定单元格之间动态添加新单元格?

标签 ios xcode ipad uitableview

我需要在选择表格单元格时添加一个新单元格。新单元格应位于所选单元格下方。我们能做到吗?

下面是我创建 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/

相关文章:

ios - 如何更改应用的捆绑ID和应用名称

ios - 每次进行更改时预览都会出错 (SwiftUI)

iphone viewForZoomingInScrollView 未调用

ios - Playground 执行失败 : error: Couldn't lookup symbols

ios - 更改按钮 anchor SwiftUI

ios - 自定义框架无法在 iOS 模拟器中加载(错误的架构)

iphone - 我的网站在 ipad/iphone 上非常滞后,删除了 css 效果和 javascript

iphone - iPhone-在iOS 3.x上检测单击和长按

html - 固定导航在移动设备上滚动时失去焦点

xcode - 如何获取 Xcode 8 的 clang 格式?