Reputation: 57
I used a UICollectionView and I used the cells to place a label which I associate my value. When you plug the cell I want to take the text to the selected label and use it to do anything else. How can I do?
With this code, I can go back to the index exactly, but I can not take the contents of the cell and put it in a string.
- (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);
}
Upvotes: 2
Views: 2153
Reputation: 726579
This line
CustomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
does not give you the item that has been selected, it gives you an unused cell that has been recycled. You need to call
CustomCell *cell = [collectionView.dataSource collectionView:collectionView cellForItemAtIndexPath:indexPath];
to get the correct cell.
However, fundamentally, this is a wrong approach: you should use the indexPath
to query the model for the text of the label, rather than asking the view. Take a look at the code of your collectionView:cellForItemAtIndexPath
method, and find the place where you use indexPath
to set the text of the label. The text comes from your model classes. You should do the same thing in your didSelectItemAtIndexPath
method.
Upvotes: 5
Reputation: 342
assing tag value when you creating the UILabel
Then in your code you can get the label
- (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);
}
I hope this helps.
Upvotes: 1