如何增加一个NSIndexPath

6
今日免费次数已满, 请开通会员/明日再来
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个回答

6
你可以尝试这个方法 - 或许同样有些笨拙,但至少更加简洁一些:
NSInteger newLast = [indexPath indexAtPosition:indexPath.length-1]+1;
indexPath = [[indexPath indexPathByRemovingLastIndex] indexPathByAddingIndex:newLast];

很好,我喜欢它,因为它避免了与C数组的所有无用操作。谢谢你。 - drekka

5
这样可以减少一行代码: indexPath = [NSIndexPath indexPathForRow:indexPath.row+1 inSection:actualIndexPath.section];

它涉及到IT技术。

这将适用于表视图索引路径,但如果我记得正确,我考虑过一种情况,即索引路径是针对其他内容且超过两个节点的。 - drekka

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中,使用嵌套的UITableView实现类似的结果的for循环,通过遍历for循环,将单元格的详细文本填充为“行已更新”。
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)                            
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接