ios 如何为 TableView 创建 NSIndexPath

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2151196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 16:50:04  来源:igfitidea点击:

How to create NSIndexPath for TableView

iosiphoneuitableviewnsindexpath

提问by Rubber Duck

I need delete row 1 of a table in a function I have defined. In order to use deleteRowAtIndexPathyou must use an IndexPathwith a section and row defined. How can I create an indexpath like this?

我需要在我定义的函数中删除表的第 1 行。为了使用,deleteRowAtIndexPath您必须使用IndexPath定义了节和行的 。如何创建这样的索引路径?

An array with the int {1} as its only member will crash; the NSLog message states that the section needs to be defined as well.

以 int {1} 作为唯一成员的数组会崩溃;NSLog 消息指出该部分也需要定义。

*Edit -> Code relating to cell delete:

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

    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];

回答by Ben Gottlieb

Use [NSIndexPath indexPathForRow:inSection:]to quickly create an index path.

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

Edit:In Swift 3:

编辑:在 Swift 3 中:

let indexPath = IndexPath(row: rowIndex, section: sectionIndex)

Swift 5

斯威夫特 5

IndexPath(row: 0, section: 0)

回答by verec

indexPathForRowis a class method!

indexPathForRow是一个类方法!

The code should read:

代码应为:

NSIndexPath *myIP = [NSIndexPath indexPathForRow:0 inSection:0] ;

回答by JohnVanDijk

Obligatory answer in Swift : NSIndexPath(forRow:row, inSection: section)

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

You will notice that NSIndexPath.indexPathForRow(row, inSection: section)is not available in swift and you must use the first method to construct the indexPath.

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

回答by comrade

For Swift 3 it's now: IndexPath(row: rowIndex, section: sectionIndex)

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