web-dev-qa-db-ja.com

複数のセクションを持つUITableviewの行番号を取得します

UITableViewがあり、その中に複数のセクションがあり、各セクションには複数の行があります。セクションだけでなく、テーブル全体に関する選択したセルの行番号を取得したいと思います。

例:

  1. UITableViewに2つのセクションがあり、セクション1には3行、セクション2には5行があります。
  2. セクション2の2番目の行を選択する場合、(セクションに関する)行番号として2を取得するのではなく、didSelectRowAtIndexPathメソッドの行番号として5を取得する必要があります。

次のようにして自分で行番号を取得しようとしましたが、機能しないようです。

- (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.rowtheRowに格納しようとするとコードがクラッシュします。

助けてください。ありがとうございました

13
hyd00
NSInteger rowNumber = 0;

for (NSInteger i = 0; i < indexPath.section; i++) {
    rowNumber += [self tableView:tableView numberOfRowsInSection:i];
}

rowNumber += indexPath.row;
44
Wain

これがSwift 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
}
9
PJeremyMalouf

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...
}
8
Max Masnick

私はビッグデータセットを持っていて、forループを使用した以前の回答は、下のセクションでパフォーマンスの問題を引き起こしていました。事前に計算をして、少しスピードアップしました。

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
    }
}
2
SirRupertIII

以下のコードをdidSelectRowAt/didSelectItemAtコールバックに実装するとします。

UITableView

var index: Int = indexPath.row
for i in 0..<indexPath.section {
    index += collectionView.numberOfRows(inSection: i)
}

UICollectionView

var index: Int = indexPath.item
for i in 0..<indexPath.section {
    index += collectionView.numberOfItems(inSection: i)
}

例:2つのセクション、それぞれ3つの行(アイテム)。セクション1で選択された行(アイテム)1、index = 4

0
Jakub Truhlář