如何为TableView创建NSIndexPath

Rub*_*uck 242 iphone uitableview nsindexpath ios

我需要在我定义的函数中删除表的第1行.要使用deleteRowAtIndexPath,必须使用IndexPath带有定义的部分和行.如何创建这样的索引路径?

以int {1}为唯一成员的数组将崩溃; NSLog消息表明该部分也需要定义.

*编辑 - >与删除单元格相关的代码:

    NSIndexPath *myIP = [[NSIndexPath alloc] indexPathForRow:0 inSection:0];
    NSArray *myArray = [[NSArray alloc] initWithObjects:myIP, nil];
//  [self.tableView beginUpdates];
    [self.tableView deleteRowsAtIndexPaths:myArray withRowAnimation:UITableViewRowAnimationFade];
//  [self.tableView endUpdates];
Run Code Online (Sandbox Code Playgroud)

Ben*_*ieb 644

使用[NSIndexPath indexPathForRow:inSection:]快速创建一个索引路径.

编辑:在Swift 3中:

let indexPath = IndexPath(row: rowIndex, section: sectionIndex)
Run Code Online (Sandbox Code Playgroud)

  • 如果您同时瞄准iOS和Mac平台,则NSIndexPath UIKit扩展不可用,因此您需要使用以下代码(其功能与`indexPathForRow:inSection:`方法相同):`NSUInteger indexes [] = { section,row}; NSIndexPath*indexPath = [NSIndexPath indexPathWithIndexes:索引长度:2];` (11认同)
  • 谢谢回复.该程序仍然崩溃 - NSLog报告:***由于未捕获的异常'NSInvalidArgumentException'终止应用程序,原因:'*** - [NSIndexPath indexPathForRow:inSection:]:发送到实例的无法识别的选择器 (2认同)

ver*_*rec 117

indexPathForRow 是一种类方法!

代码应为:

NSIndexPath *myIP = [NSIndexPath indexPathForRow:0 inSection:0] ;
Run Code Online (Sandbox Code Playgroud)


Joh*_*ijk 18

Swift中的强制性答案: NSIndexPath(forRow:row, inSection: section)

您会注意到NSIndexPath.indexPathForRow(row, inSection: section)在swift中不可用,您必须使用第一种方法来构造indexPath.


com*_*ade 17

对于Swift 3,它现在是: IndexPath(row: rowIndex, section: sectionIndex)

  • 感谢您添加Swift 3.编译器抱怨我`let cell = self.myTableView.cellForRow(at:NSIndexPath(row:0,section:1))`并将其更改为`let cell3 = self.myTableView.cellForRow( at:IndexPath(row:0,section:1))`,所以它们似乎从NSIndexPath迁移到IndexPath (6认同)