gpt4 book ai didi

ios - 复制 UITableViewCells 错误

转载 作者:行者123 更新时间:2023-11-29 02:50:45 25 4
gpt4 key购买 nike

我有一个包含大约 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com