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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5774939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 19:42:26  来源:igfitidea点击:

iOS - How can I get the IndexPath of the last item in a tableview?

iphoneobjective-cioscocoa-touch

提问by Nick

I would like to automatically scroll to the end of a table view.

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

[tableView scrollToRowAtIndexPath:lastIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];

Given that I know how many item are in the tableview using:

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

How can I get the IndexPath * to the last item in this tableView? This is needed so that I can provide it as an argument to scrollToRowAtIndexPath:atScrollPosition:animated

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

Thanks!

谢谢!

回答by Ryan Grimm

To get a reference to the last row in the last section…

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

// 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];

回答by EmptyStack

You can get the indexPathof the last row in last section like this.

您可以像这样获取最后一节中最后一行的indexPath

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:(numberOfRowsInLastSection - 1) inSection:(numberOfSections - 1)];

Here, numberOfSectionsis the value you return from numberOfSectionsInTableView:method. And, numberOfRowsInLastSectionis the value you return from numberOfRowsInSection:method for the last section in the table view.

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

This can be placed in a subclass or category to make it easy:

这可以放在子类或类别中以​​使其变得容易:

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

回答by Omer Janjua

In swift 3

在迅捷 3

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

if (indexPath.row == lastRowIndex - 1) {
     print("last row selected")
}

回答by CodeBender

Here is an extension in Swift 4.xthat takes into consideration that there may not be any rows, so it avoids out of range crashes.

这是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)
    }
}

Then call it from your viewcontroller with:

然后从您的视图控制器调用它:

let lastIndexPath = tableView.lastIndexPath()

回答by Shmidt

Probably someone will need the same for UICollectionView, so I updated Ryan Grimm's answer for it:

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

NSInteger lastSectionIndex = [self.collectionView numberOfSections] - 1;
NSInteger lastItemIndex = [self.collectionView numberOfItemsInSection:lastSectionIndex] - 1;
NSIndexPath *pathToLastItem = [NSIndexPath indexPathForItem:lastItemIndex inSection:lastSectionIndex];

回答by Meghan

try this:

尝试这个:

In cellForRowAtIndexPath

cellForRowAtIndexPath

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

{
     myIndexPath = indexpath;
}

myIndexPath should be object of NSIndexPath

myIndexPath 应该是对象 NSIndexPath

回答by johnpatrickmorgan

Most of the answers here, including the accepted answer, do not take into account the valid cases of a table view with zero sections, or a final section with zero rows.

此处的大多数答案,包括已接受的答案,都没有考虑具有零部分的表格视图或具有零行的最后一部分的有效情况。

The best way to represent those situations is using an index of NSNotFound, which is accepted by UIKit in methods such as scrollToRowAtIndexPath:atScrollPosition:animated:.

表示这些情况的最好方法是使用 的索引NSNotFound,UIKit 在诸如scrollToRowAtIndexPath:atScrollPosition:animated:.

NSNotFound is a valid row index for scrolling to a section with zero rows.

NSNotFound 是滚动到零行部分的有效行索引。

I use the following method:

我使用以下方法:

- (NSIndexPath *)bottomIndexPathOfTableView:(UITableView *)tableView
{
    NSInteger finalSection = NSNotFound;
    NSInteger finalRow = NSNotFound;

    NSInteger numberOfSections = [tableView numberOfSections];
    if (numberOfSections)
    {
        finalSection = numberOfSections - 1;
        NSInteger numberOfRows = [tableView numberOfRowsInSection:finalSection];
        if (numberOfRows)
        {
            finalRow = numberOfRows - 1;
        }
    }
    return numberOfSections ? [NSIndexPath indexPathForRow:finalRow inSection:finalSection] : nil;
}

回答by alexburtnik

It seems like all the solutions don't consider that the last section may have no rows at all. So here is a function which returns the last row in a last non-empty section:

似乎所有解决方案都没有考虑到最后一部分可能根本没有行。所以这是一个函数,它返回最后一个非空部分的最后一行:

Swift 3:

斯威夫特 3:

extension UITableViewDataSource {
    func lastIndexPath(_ tableView: UITableView) -> IndexPath? {
        guard let sections = self.numberOfSections?(in: tableView) else { return nil }
        for section in stride(from: sections-1, through: 0, by: -1) {
            let rows = self.tableView(tableView, numberOfRowsInSection: section)
            if rows > 0 {
                return IndexPath(row: rows - 1, section: section)
            }
        }
        return nil
    }
}

Example:

例子:

class ViewController: UIViewController {

    //...

    func scrollToLastRow() {
        if let indexPath = lastIndexPath(tableView) {
            tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)
        }
    }
}

extension ViewController: UITableViewDataSource {
    //required data source methods
}

回答by Mark Bridges

Swift 3 answer, with out of bounds checks. Implemented as a tableview extension

Swift 3 答案,带有越界检查。作为 tableview 扩展实现

extension UITableView {

    var lastIndexPath: IndexPath? {

        let lastSectionIndex = numberOfSections - 1
        guard lastSectionIndex >= 0 else { return nil }

        let lastIndexInLastSection = numberOfRows(inSection: lastSectionIndex) - 1
        guard lastIndexInLastSection >= 0 else { return nil }

        return IndexPath(row: lastIndexInLastSection, section: lastSectionIndex)
    }
}

回答by Brijesh Shiroya

Try this code:

试试这个代码:

//   get number of section
let indexOfLastSection = self.yourTableView.numberOfSections - 1

// Then get the number of rows in the last section

if indexOfLastSection >= 0{
    let indexOfLastRow = self.yourTableView.numberOfRows(inSection: indexOfLastSection) - 1
    if indexOfLastRow >= 0{
        let pathToLastRow = IndexPath.init(row: indexOfLastRow, section: indexOfLastSection)
    }
}