ios - 复制 UITableViewCells 错误

标签 ios objective-c uitableview ios7 copy

我有一个包含大约 15 个项目的 UITableView。我想长按单元格以查看复制菜单项以复制单元格的内容并将其插入到从中复制的单元格的正下方。这是我的代码;

- (void)tableView:(UITableView*)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath*)indexPath withSender:(id)sender
{
    // Insert the copied item below the item where it was copied from
    if (action == @selector(copy:)) {
        UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
        self.copiedColor = cell.textLabel.text;

        [self.colors addObject:self.copiedColor];
        NSIndexPath *path = [NSIndexPath indexPathForRow:indexPath.row inSection:0];

        [self.tableView beginUpdates];
        [tableView insertRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationBottom];
        [self.tableView endUpdates];
    }
}

- (BOOL)tableView:(UITableView*)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath*)indexPath withSender:(id)sender
{
    // Show the copy menu item for cells
    if (action == @selector(copy:)) {
        return YES;
    }

    return NO;
}

- (BOOL)tableView:(UITableView*)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath*)indexPath
{
    return YES;
}

出现复制菜单,我可以毫无问题地复制内容。问题出在插入部分。它实际上插入了单元格,但内容有时会弄乱。例如,我在这里复制颜色深红色。它被复制并且新单元格出现在原始单元格下方。但请注意,另一个带有 Crimson 的单元格出现在最后一行!

enter image description here enter image description here

如果我复制颜色 Beige,它没有被复制,Aqua 被复制但也没有出现。这又是一团糟!

enter image description here enter image description here

谁能告诉我如何纠正这个问题?

如果通过我发布的代码和图片很难理解它,我上传了一个测试可运行的 xcode 项目 here来演示这个问题。请看一下。

提前非常感谢。

最佳答案

我认为这一行:

[self.colors addObject:self.copiedColor];

应该是:

[self.colors insertObject: self.copiedColor atIndex: [indexPath row]];

否则,您会一直在颜色数组的末尾添加对象,但在 TableView 中,您将它们插入到不同的索引处,因此数据源和 TableView 在某种程度上变得不同步。

还有这一行:

[tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

您可以简单地更改为:

[tableView dequeueReusableCellWithIdentifier:@"cell"];

对于您遇到的其他奇怪行为。此外,在你的情况下检查 cell 是否为 nil 是没有必要的,因为你已经在 Storyboard中声明了单元格的原型(prototype)并且该方法不会返回 nil

关于ios - 复制 UITableViewCells 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24572264/

相关文章:

ios - tableviewcell 内的 UIButtons 和 UILabels

objective-c - 可变返回类型 Objective-C 或 c

ios - 将 UITableView 添加为 subview

ios - 在 RSS 提要中找不到缩略图元素

ios - 在预构建阶段为多个目标选择不同的图像源

ios - 我们可以在适用于 iOS 的企业应用中使用应用内购买吗?

ios - xcode 调试 - 快速跨过汇编代码回到我的自定义代码

ios - DistanceFromLocation错误

iphone - 如何将数据包装在iPhone单元格的标签中?

ios - 为什么滚动 UITableView 比滚动 UIScrollView 响应更快?