ios - 使用 sections 将 indexPath 减一

标签 ios objective-c iphone cocoa-touch uitableview

我有一个包含部分的 UITableView,我想知道给定 IndexPath 的前一项,我知道我可以使用它

NSIndexPath* newIndexPath = [NSIndexPath indexPathForRow:oldIndexPath.row -1 inSection:oldIndexPath.section];

如果我只有一个部分,但是因为我有几个部分,我怎么知道tableview中的上一个项目(如果该项目在他的部分中是第一个我想得到上一个部分的最后一个项目。

谢谢。

最佳答案

我认为您可以使用类似的方法:(如果您在接收 UITableView 的方法中使用此代码,则将 self.tableView 替换为 tableView 对象作为参数):

NSIndexPath* newIndexPath = nil;
// check for row being the first one in this section
if (oldIndexPath.row == 0) {
    // check for this section having a previous section
    if (oldIndexPath.section > 0) {
        // get number of rows of the previous section
        NSInteger numberOfRows = [self.tableView numberOfRowsInSection : oldIndexPath.section - 1];
        newIndexPath = [NSIndexPath indexPathForRow: numberOfRows - 1 inSection: oldIndexPath.section - 1];
    }
} else { // if the row is not the first in this section
    // get the indexPath for the previous row in this section
    newIndexPath = [NSIndexPath indexPathForRow:oldIndexPath.row - 1 inSection: oldIndexPath.section];
}

关于ios - 使用 sections 将 indexPath 减一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27423567/

相关文章:

iphone - OpenGL ES 和现实世界的开发

ios - SwfUpload Flash uploader 在 IOS 中不可见且无法工作

ios - ReactJS 未在第一代 iPad 上加载元素

ios - 只为 UITableView 的一个方向启用弹跳

ios - 如何在 iOS 中发送和接收 Web 服务请求和响应?

iphone - 如何避免父类(super class)方法被 objective-c 中的子类覆盖

objective-c - iOS6 和 ACAccount : Twitter type disappears?

ios - UIPrintInteractionController 不显示本地化文本

objective-c - 为 PubNub 对象初始化时,Secret Key 去了哪里?

iphone - iOS 在 iPad 上触摸(自动)偏移