IOS. Как я могу получить IndexPath последнего элемента в представлении таблицы?
Я хотел бы автоматически прокрутить до конца представления таблицы.
[tableView scrollToRowAtIndexPath:lastIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
Учитывая, что я знаю, сколько элементов находится в представлении таблицы, используя:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
Как я могу получить IndexPath * для последнего элемента в этом таблицеView? Это необходимо, так что я могу предоставить его как аргумент scrollToRowAtIndexPath: atScrollPosition: анимированный
Спасибо!
Ответы
Ответ 1
Вы можете получить indexPath последней строки в последнем разделе, как это.
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:(numberOfRowsInLastSection - 1) inSection:(numberOfSections - 1)];
Здесь numberOfSections - это значение, возвращаемое из метода numberOfSectionsInTableView:
. И numberOfRowsInLastSection - это значение, которое вы возвращаете из метода numberOfRowsInSection:
для последнего раздела в представлении таблицы.
Это можно поместить в подкласс или категорию, чтобы упростить его:
-(NSIndexPath*)indexPathForLastRow
{
return [NSIndexPath indexPathForRow:[self numberOfRowsInSection:self.numberOfSections - 1] - 1 inSection:self.numberOfSections - 1];
}
Ответ 2
Чтобы получить ссылку на последнюю строку в последнем разделе...
// 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];
Ответ 3
В быстрой 3
let lastRowIndex = tableView.numberOfRows(inSection: tableView.numberOfSections-1)
if (indexPath.row == lastRowIndex - 1) {
print("last row selected")
}
Ответ 4
Возможно, кому-то понадобится то же самое для UICollectionView
,
поэтому я обновил Ryan Grimm для этого:
NSInteger lastSectionIndex = [self.collectionView numberOfSections] - 1;
NSInteger lastItemIndex = [self.collectionView numberOfItemsInSection:lastSectionIndex] - 1;
NSIndexPath *pathToLastItem = [NSIndexPath indexPathForItem:lastItemIndex inSection:lastSectionIndex];
Ответ 5
попробуйте следующее:
В cellForRowAtIndexPath
if(indexPath.row == myArray.count -1)
{
myIndexPath = indexpath;
}
myIndexPath должен быть объектом NSIndexPath
Ответ 6
Большинство ответов здесь, включая принятый ответ, не учитывают действительные случаи табличного представления с нулевыми разделами или конечный раздел с нулевыми строками.
Лучшим способом представления этих ситуаций является использование индекса NSNotFound
, который принимается UIKit в таких методах, как scrollToRowAtIndexPath:atScrollPosition:animated:
.
NSNotFound - допустимый индекс строки для прокрутки к разделу с нулевыми строками.
Я использую следующий метод:
- (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;
}
Ответ 7
Вот расширение в Swift, которое учитывает, что не может быть никаких разделов или строк, поэтому он избегает сбоев в работе диапазона.
extension UITableView {
func lastIndexpath() -> NSIndexPath {
let section = self.numberOfSections > 0 ? self.numberOfSections - 1 : 0
let row = self.numberOfRowsInSection(section) > 0 ? self.numberOfRowsInSection(section) - 1 : 0
return NSIndexPath(forItem: row, inSection: section)
}
}
Затем вызовите его из вашего диспетчера view с помощью:
let lastIndexPath = tableView.lastIndexPath()
Ответ 8
Свифт 3, с проверками вне границ. Реализован как расширение таблицы
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)
}
}
Ответ 9
Кажется, что все решения не учитывают, что последний раздел не может содержать никаких строк. Итак, вот функция, которая возвращает последнюю строку в последнем непустом разделе:
Swift 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, to: 0, by: -1) {
let rows = self.tableView(tableView, numberOfRowsInSection: section)
if rows > 0 {
return IndexPath(row: rows - 1, section: section)
}
}
return nil
}
}
Пример:
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
}
Ответ 10
Попробуйте этот код:
// 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)
}
}