iphone - 如何正确使用 insertRowsAtIndexPaths?

标签 iphone objective-c xcode uitableview

我浏览了所有在线示例,但无法弄清楚如何正确地将单元格添加到带有动画的 TableView 中。假设我有一个包含一个单元格的部分,我想在用户点击第一个单元格的附件后添加另一个单元格。

我的“添加”方法是这样做的:

- (IBAction) toggleEnabledTextForSwitch1onSomeLabel: (id) sender {  
if (switch1.on) {

    NSArray *appleComputers = [NSArray arrayWithObjects:@"WWWWW" ,@"XXXX", @"YYYY", @"ZZZZ", nil];
    NSDictionary *appleComputersDict = [NSDictionary dictionaryWithObject:appleComputers forKey:@"Computers"];
    [listOfItems replaceObjectAtIndex:0 withObject:appleComputersDict];
    [tblSimpleTable reloadData];

}

哪个有效但没有动画。我知道为了添加动画,我需要使用 insertRowsAtIndexPaths:withRowAnimation,所以我尝试了很多选项,但在执行 insertRowsAtIndexPaths:withRowAnimation 方法时它总是崩溃。

我最近的尝试是这样做的:

- (IBAction) toggleEnabledTextForSwitch1onSomeLabel: (id) sender {  
if (switch1.on) {

    NSIndexPath *path1 = [NSIndexPath indexPathForRow:1 inSection:0]; //ALSO TRIED WITH indexPathRow:0
      NSArray *indexArray = [NSArray arrayWithObjects:path1,nil];   
     [tblSimpleTable insertRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationRight];

}
}  

我做错了什么?我怎样才能让这件事轻松发生?我不明白这整个 indexPathForRow 事情......我也不明白如何使用这种方法将标签名称添加到新单元格。请帮助...谢谢!!

最佳答案

这是一个两步过程:

首先更新您的数据源,以便 numberOfRowsInSectioncellForRowAtIndexPath 将为您的插入后数据返回正确的值。您必须在插入或删除行之前执行此操作,否则您将看到您收到的“行数无效”错误。

然后插入你的行:

[tblSimpleTable beginUpdates];
[tblSimpleTable insertRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationRight];
[tblSimpleTable endUpdates];

简单地插入或删除一行不会改变您的数据源;你必须自己做。

关于iphone - 如何正确使用 insertRowsAtIndexPaths?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6943470/

相关文章:

iphone - Xcode 无法识别图像大小的变化

ios - 为什么我的 Tab Bar 没有出现在模拟器中?

objective-c - init 方法返回不同类型的对象是否是可接受的模式?

ios - 为 iPhone (iOS 6+) 修改 sms.db

iphone - 点击时自动选择文本字段中的文本

ios - 如何从音频记录生成签名(类似于 Shazam)

objective-c - 在屏幕保护程序中嵌入自定义字体

ios - UIKeyboardWillChangeFrameNotification 并不总是被调用

iphone - 为什么要在 init 方法中调用 autorelease 来定义 iVar?

iphone - 设置包中的更新版本失败 iphone