Ответ 1
NSInteger rowNumber = 0;
for (NSInteger i = 0; i < indexPath.section; i++) {
rowNumber += [self tableView:tableView numberOfRowsInSection:i];
}
rowNumber += indexPath.row;
У меня есть UITableView
, с несколькими разделами в нем, и каждый раздел имеет несколько строк. Я хочу получить номер строки выбранной ячейки относительно всей таблицы, а не только раздела.
Пример:
UITableView
, в разделе 1 есть 3 строки, а в разделе 2 - 5 строк.didSelectRowAtIndexPath
, вместо того, чтобы получать 2 в качестве номера строки (что относится к разделу).Я попытался получить номер строки самостоятельно, выполнив следующее, но, похоже, не работает:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
NSLog(@"%d",indexPath.row);
int theRow = indexPath.row;
NSLog(@"%d",theRow);
}
Я думал о сохранении номера строки в переменной int
, а затем сам добавлял номера строк, но при сбое кода indexpath.row
в theRow
происходит сбой кода.
Пожалуйста, помогите. Спасибо вам
NSInteger rowNumber = 0;
for (NSInteger i = 0; i < indexPath.section; i++) {
rowNumber += [self tableView:tableView numberOfRowsInSection:i];
}
rowNumber += indexPath.row;
Вот быстрая адаптация вышеупомянутого ответа Wain
class func returnPositionForThisIndexPath(indexPath:NSIndexPath, insideThisTable theTable:UITableView)->Int{
var i = 0
var rowCount = 0
while i < indexPath.section {
rowCount += theTable.numberOfRowsInSection(i)
i++
}
rowCount += indexPath.row
return rowCount
}
Здесь более чистая реализация этой концепции в Swift:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->
var rowNumber = indexPath.row
for i in 0..<indexPath.section {
rowNumber += self.tableView.numberOfRowsInSection(i)
}
// Do whatever here...
}
У меня был большой набор данных, а предыдущие ответы, используемые для циклов, вызывали проблемы с производительностью для меня в нижних разделах. Я закончил тем, что делал расчет заранее, и немного ускорил процесс.
private var sectionCounts = [Int:Int]()
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let number = fetchedResultsController.sections?[section].numberOfObjects ?? 0
if section == 0 {
sectionCounts[section] = number
} else {
sectionCounts[section] = number + (sectionCounts[section-1] ?? 0)
}
return number
}
func totalRowIndex(forIndexPath indexPath: NSIndexPath) -> Int {
if indexPath.section == 0 {
return indexPath.row
} else {
return (sectionCounts[indexPath.section-1] ?? 0) + indexPath.row
}
}
Скажем, я реализую код ниже в didSelectRowAt
/didSelectItemAt
обратных вызовах...
var index: Int = indexPath.row
for i in 0..<indexPath.section {
index += collectionView.numberOfRows(inSection: i)
}
var index: Int = indexPath.item
for i in 0..<indexPath.section {
index += collectionView.numberOfItems(inSection: i)
}
Пример: 2 секции, по 3 строки (позиции). Выбранная строка (позиция) 1 в разделе 1,
index
= 4
Я не знаю о нескольких разделах, но могу дать вам один раздел...
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger index=indexPath.row;
NSString *string=[[NSString alloc]initWithFormat:@"%ld",(long)index];
}
из этого вы можете получить номер строки, и вы можете сохранить его в строке....