iOS - 如何获取tableview中最后一项的IndexPath?

Nic*_*ick 25 iphone cocoa-touch objective-c ios

我想自动滚动到表格视图的末尾.

[tableView scrollToRowAtIndexPath:lastIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
Run Code Online (Sandbox Code Playgroud)

鉴于我知道tableview中有多少项使用:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
Run Code Online (Sandbox Code Playgroud)

如何将IndexPath*转换为此tableView中的最后一项?这是必需的,以便我可以将它作为scrollToRowAtIndexPath的参数提供:atScrollPosition:animated

谢谢!

Rya*_*imm 31

要获得对最后一节中最后一行的引用...

// First figure out how many sections there are
NSInteger lastSectionIndex = [tableView numberOfSections] - 1;

// Then grab the number of rows in the last section
NSInteger lastRowIndex = [tableView numberOfRowsInSection:lastSectionIndex] - 1;

// Now just construct the index path
NSIndexPath *pathToLastRow = [NSIndexPath indexPathForRow:lastRowIndex inSection:lastSectionIndex];
Run Code Online (Sandbox Code Playgroud)


Emp*_*ack 30

您可以像这样获取上一部分中最后一行的indexPath.

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:(numberOfRowsInLastSection - 1) inSection:(numberOfSections - 1)];
Run Code Online (Sandbox Code Playgroud)

这里,numberOfSections是您从numberOfSectionsInTableView:方法返回的值.并且,numberOfRowsInLastSection是您从numberOfRowsInSection:表视图中的最后一个部分的方法返回的值.

这可以放在子类或类别中以​​简化:

-(NSIndexPath*)indexPathForLastRow
{
    return [NSIndexPath indexPathForRow:[self numberOfRowsInSection:self.numberOfSections - 1] - 1 inSection:self.numberOfSections - 1];
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,如果最后一部分没有行,则会出错 (2认同)

Ome*_*jua 10

在快速3

let lastRowIndex = tableView.numberOfRows(inSection: tableView.numberOfSections-1)

if (indexPath.row == lastRowIndex - 1) {
     print("last row selected")
}
Run Code Online (Sandbox Code Playgroud)


Shm*_*idt 9

可能有人会需要同样的UICollectionView,所以我更新了Ryan Grimm的答案:

NSInteger lastSectionIndex = [self.collectionView numberOfSections] - 1;
NSInteger lastItemIndex = [self.collectionView numberOfItemsInSection:lastSectionIndex] - 1;
NSIndexPath *pathToLastItem = [NSIndexPath indexPathForItem:lastItemIndex inSection:lastSectionIndex];
Run Code Online (Sandbox Code Playgroud)


Meg*_*han 8

试试这个:

cellForRowAtIndexPath

if(indexPath.row == myArray.count -1)

{
     myIndexPath = indexpath;
}
Run Code Online (Sandbox Code Playgroud)

myIndexPath应该是对象 NSIndexPath


Cod*_*der 8

这是Swift 4.x中的扩展,考虑到可能没有任何行,因此它避免了超出范围的崩溃.

import UIKit

extension UITableView {
    func lastIndexpath() -> IndexPath {
        let section = max(numberOfSections - 1, 0)
        let row = max(numberOfRows(inSection: section) - 1, 0)

        return IndexPath(row: row, section: section)
    }
}
Run Code Online (Sandbox Code Playgroud)

然后从viewcontroller中调用它:

let lastIndexPath = tableView.lastIndexPath()
Run Code Online (Sandbox Code Playgroud)