如何增加NSIndexPath

问题描述 投票:6回答:4

我有一个数据情况,我想使用索引路径。当我遍历数据时,我想增加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);

这感觉有点,嗯,笨重 - 有更好的方法吗?

objective-c ios nsindexpath
4个回答
6
投票

你可以尝试这个 - 也许同样笨重,但至少有点短:

NSInteger newLast = [indexPath indexAtPosition:indexPath.length-1]+1;
indexPath = [[indexPath indexPathByRemovingLastIndex] indexPathByAddingIndex:newLast];

5
投票

少行一行:

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


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
}

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)                            
}
© www.soinside.com 2019 - 2024. All rights reserved.