2017-07-15 9 views
0

次の実装では、選択した各セルのindexPathとtableView全体で選択されたアイテムの合計数を追跡することができました。各セクションで選択された項目の数

各セクションで選択したアイテムの数をどのように取得できるのでしょうか?ここで

- (void)selectedItem: (UITableView *)tableView { 
    NSArray <NSIndexPath*> *selectedIndexPaths = [tableView indexPathsForSelectedRows]; 
    for (NSIndexPath *indexpath in selectedIndexPaths) { 
     NSLog(@"Section index : %ld", indexpath.section); 
     NSLog(@"Row index : %ld", indexpath.row); 
    } 
} 

あなたは、私がセクション0で2つの項目、およびセクション内の1つのアイテムを選択することを見ることができ、プリントアウトで1

po [tableView indexPathsForSelectedRows] 
<__NSArrayI 0x1744428b0>(
<NSIndexPath: 0xc000000000400016> {length = 2, path = 0 - 2}, 
<NSIndexPath: 0xc000000000c00016> {length = 2, path = 0 - 6}, 
<NSIndexPath: 0xc000000001000116> {length = 2, path = 1 - 8} 
) 
+0

私はあなたが持っているindexpathから手動で行う必要があると思うと思います –

+0

あなたは説明していただけますか? – hotspring

+0

あなたはセルセクションの選択の独自のリストを管理するか、indexPathsをループしてグループ化する必要があります。 –

答えて

1
NSMutableDictionary *selectedRowsInSectionDictionary = [NSMutableDictionary dictionary]; 
NSArray <NSIndexPath*> *selectedIndexPaths = [tableview indexPathsForSelectedRows]; 
for (NSIndexPath *indexpath in selectedIndexPaths) { 
    NSInteger numberOfSelectedRows = [[selectedRowsInSectionDictionary objectForKey: @(indexpath.section)] integerValue]; 
    numberOfSelectedRows++; 
    [selectedRowsInSectionDictionary setObject:@(numberOfSelectedRows) forKey: @(indexpath.section)]; 
} 

あなたはで選択された行数を取得しますsectionNumberをキーとし、そのセクションの選択された行の数をselectedRowsInSectionDictionary辞書の値として持つセクション。

+0

FYI - '[NSNumber numberWithInteger:numberOfSelectedRows]'を '@(numberOfSelectedRows)'に置き換えることができます。 – rmaddy

+0

そして、キーの文字列にセクションを変換する必要はありません。キーとして '@(indexpath.section)'を使います。辞書キーをplistファイルに書きたい場合は、辞書キーは文字列でなければなりません。 – rmaddy

+0

@rmaddyは、 'valueForKeyPath'の' @ count'機能を使って各セクションのselectedItemの数を取得するために1行のコードを使用する方法があります。またはより良いアイデア? – hotspring

関連する問題