2

UICollectionView を使用し、セルを使用して値を関連付けるラベルを配置しました。セルを接続すると、テキストを選択したラベルに取り、それを使用して他のことをしたいと思います。どのようにできるのか?

このコードでは、インデックスに正確に戻ることができますが、セルの内容を取得して文字列に入れることはできません。

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSString *CellIdentifier = @"Cell";
    CustomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];

    NSString *strColorCell = cell.lblCustomCell.text;
    NSLog(@"Indice della cella: %i %i %@", indexPath.item, indexPath.section * 2 + indexPath.row, strColorCell);
}
4

2 に答える 2

5

この行

CustomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];

は、選択されたアイテムを提供するのではなく、リサイクルされた未使用のセルを提供します。電話する必要があります

CustomCell *cell = [collectionView.dataSource collectionView:collectionView cellForItemAtIndexPath:indexPath];

正しいセルを取得します。

ただし、基本的に、これは間違ったアプローチですindexPath。 ビューに問い合わせるのではなく、 を使用してモデルにラベルのテキストを問い合わせるべきです。メソッドのコードを見て、ラベルのテキストを設定するためにcollectionView:cellForItemAtIndexPath使用する場所を見つけてください。indexPathテキストはモデル クラスから取得されます。メソッドで同じことを行う必要がありますdidSelectItemAtIndexPath

于 2013-10-09T10:43:11.773 に答える
1

作成時にタグ値を割り当てるUILabel

次に、コードでラベルを取得できます

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    UILabel *custLabel = (UILabel*)[cell viewWithTag:labelTag];
    NSString *strColorCell = custLabel.text;
    NSLog(@"Indice della cella: %i %i %@", indexPath.item, indexPath.section * 2 + indexPath.row, strColorCell);
}

これが役立つことを願っています。

于 2013-10-09T10:42:47.267 に答える