6

我有一种数据情况,我想使用索引路径。当我遍历数据时,我想增加 NSIndexPath 的最后一个节点。我到目前为止的代码是:

int nbrIndex = [indexPath length];
NSUInteger *indexArray = (NSUInteger *)calloc(sizeof(NSUInteger),nbrIndex);
[indexPath getIndexes:indexArray];
indexArray[nbrIndex - 1]++;
[indexPath release];
indexPath = [[NSIndexPath alloc] initWithIndexes:indexArray length:nbrIndex];
free(indexArray);

这感觉有点笨拙-有更好的方法吗?

4

4 回答 4

6

你可以试试这个——也许同样笨重,但至少短一点:

NSInteger newLast = [indexPath indexAtPosition:indexPath.length-1]+1;
indexPath = [[indexPath indexPathByRemovingLastIndex] indexPathByAddingIndex:newLast];
于 2012-03-09T15:01:30.960 回答
5

这样少一行:

indexPath = [NSIndexPath indexPathForRow:indexPath.row+1 inSection:actualIndexPath.section];

于 2012-08-09T02:25:13.053 回答
3

检查我在 Swift 上的解决方案:

func incrementIndexPath(indexPath: NSIndexPath) -> NSIndexPath? {
    var nextIndexPath: NSIndexPath?
    let rowCount = numberOfRowsInSection(indexPath.section)
    let nextRow = indexPath.row + 1
    let currentSection = indexPath.section

    if nextRow < rowCount {
        nextIndexPath = NSIndexPath(forRow: nextRow, inSection: currentSection)
    }
    else {
        let nextSection = currentSection + 1
        if nextSection < numberOfSections {
            nextIndexPath = NSIndexPath(forRow: 0, inSection: nextSection)
        }
    }

    return nextIndexPath
}
于 2015-10-30T08:19:50.767 回答
1

Swift 4 中的 for 循环使用嵌入式 UITableView 实现了类似的结果,遍历 for 循环,用“Row Updated”填充单元格的详细文本

for i in 0 ..< 9 {
     let nextRow = (indexPath?.row)! + i
     let currentSection = indexPath?.section
     let nextIndexPath = NSIndexPath(row: nextRow, section: currentSection!)

     embeddedViewController.tableView.cellForRow(at: nextIndexPath as IndexPath)?.detailTextLabel?.text = "Row Updated"

     let myTV = embeddedViewController.tableView
     myTV?.cellForRow(at: nextIndexPath as IndexPath)?.backgroundColor = UIColor.red
     myTV?.deselectRow(at: nextIndexPath as IndexPath, animated: true)                            
}
于 2018-08-31T17:18:58.630 回答