Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the name of a selected collectionviewcell?

This is a simple question that I thought would have an easy-to-find answer but didn't. I want to select a cell in a collectionview. The main problem is that I can't attach a gesture recognizer to a prototype cell. I want to grab the text from a label on the cell that is touched. I use the name in a different function in my view.

Or a simpler question: Is there a tutorial on tap selection from a list of items?

like image 622
user1195265 Avatar asked Feb 02 '13 08:02

user1195265


1 Answers

You have the method collectionView:didSelectItemAtIndexPath: in the delegate. This should fire when you collect the cell and give you the correct indexPath for that particular cell.

Use this indexPath in combination with the collectionView's cellForItemAtIndexPath: to access a particular cell.

Example:

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [self manipulateCellAtIndexPath:indexPath];
}

-(void) manipulateCellAtIndexPath:(NSIndexPath*)indexPath {
    UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
    // Now do what you want...
}

And, as long as I'm here. Swift-version:

override func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
    manipulateCellAtIndexPath(indexPath)
}

func manipulateCellAtIndexPath(indexPath: NSIndexPath) {
    if let cell = collectionView?.cellForItemAtIndexPath(indexPath) {
        // manipulate cell
    }
}
like image 101
T. Benjamin Larsen Avatar answered Oct 03 '22 23:10

T. Benjamin Larsen