简体   繁体   English

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

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

I would like to automatically scroll to the end of a table view.我想自动滚动到表格视图的末尾。

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

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

You can get the indexPath of the last row in last section like this. 您可以像这样获取上一节中最后一行的indexPath

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

Here, numberOfSections is the value you return from numberOfSectionsInTableView: method. 这里, numberOfSections是从numberOfSectionsInTableView:方法返回的值。 And, numberOfRowsInLastSection is the value you return from numberOfRowsInSection: method for the last section in the table view. 并且, 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];
}

In swift 3 在快速3

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

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

Probably someone will need the same for UICollectionView , so I updated Ryan Grimm 's answer for it: 可能有人会对UICollectionView需要相同的UICollectionView ,所以我更新了Ryan Grimm的答案:

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

try this: 尝试这个:

In cellForRowAtIndexPath cellForRowAtIndexPath

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

{
     myIndexPath = indexpath;
}

myIndexPath should be object of NSIndexPath myIndexPath应该是NSIndexPath对象

Here is an extension in Swift 4.x that 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: 然后从viewcontroller中调用它:

let lastIndexPath = tableView.lastIndexPath()

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;
}

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
}

Swift 3 answer, with out of bounds checks. Swift 3回答,超出界限检查。 Implemented as a tableview extension 实现为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)
    }
}

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

My Swift 5 implementation ensures a valid IndexPath .我的 Swift 5 实现确保了有效的IndexPath

extension UITableView {
    
    /// Returns nil if the table view has no rows.
    func kjy_indexPathOfLastRow() -> IndexPath? {
        let sectionsCount = numberOfSections
        guard sectionsCount > 0 else {
            return nil
        }
        for section in (0..<sectionsCount).reversed() {
            let rowsCount = numberOfRows(inSection: section)
            if rowsCount > 0 {
                return IndexPath(row: rowsCount - 1, section: section)
            }
        }
        return nil
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何通过indexPath获取uitableViewCell? - How can I get a uitableViewCell by indexPath? 单击tableview编辑按钮时如何获取索引路径? - How to get the indexpath when the tableview editbutton is clicked? 如何获取以编程方式在放置在iOS中的表格视图中的单元格和单元格索引路径中的滚动视图中创建的视图的位置 - How to get position of view created programmatically in scrollview placed in cell and cell indexpath in tableview in iOS iOS:Swift –无法弄清楚如何在tableView方法中使用indexPath - iOS: Swift – Can't figure out how to use indexPath in a tableView-method 如何在自定义的tableViewCell中获取UIButton的indexPath? - How can I get the indexPath of UIButton in a customized tableViewCell? IOS 7 - 如何从放置在 UITableViewCell 中的按钮获取 indexPath - IOS 7 - How to get the indexPath from button placed in UITableViewCell iOS如何获取,当前在cellForRowAtIndexPath方法中选择了indexpath行? - iOS how to get, current selected indexpath row on cellForRowAtIndexPath method? 我希望在tableview或任何其他替代后的下一个视图上获得indexpath.row - I want to get indexpath.row on next view after tableview or any other alternative 如何在特定索引路径的tableview中的单元格中插入值? - How to insert the value in cell in tableview at particular indexpath? indexpath.section ..如何在tableview中分成几部分? - indexpath.section .. how in tableview into sections?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM