UICollectionViewCell variable is nil

Discussion in 'iOS Programming' started by moonman239, Feb 22, 2014.

  1. moonman239 macrumors 68000

    Joined:
    Mar 27, 2009
    #1
    Relevant code in implementation file:

    Code:
    -(UICollectionViewCell *)visibleCellWhoseFrameContainsPoint:(CGPoint)point
    {
        UICollectionViewCell *theCell;
        for (UICollectionViewCell *cell in [self visibleCells])
        {
            if (CGRectContainsPoint([cell frame], point)) {
                theCell = cell;
                break;
            }
        }
        return theCell;
    }
    
    "theCell" appears to be nil. When I set a breakpoint to evaluate "cell" I get multiple error messages that say "'frame' has unknown return type; cast the call to its declared return type"

    After looking at this page on Stack Overflow, I believe the solution is to use the collection view's layoutAttributesForItemAtIndexPath: method.
     
  2. ChristianJapan, Feb 22, 2014
    Last edited: Feb 22, 2014

    ChristianJapan macrumors 601

    ChristianJapan

    Joined:
    May 10, 2010
    Location:
    日本
    #2
    Have a look on the method
    Code:
    - (NSIndexPath *)indexPathForItemAtPoint:(CGPoint)point
    You give in the point in CollectionView-dimension and get the indexPath back.

    And the cell if you need
    Code:
    - (UICollectionViewCell *)cellForItemAtIndexPath:(NSIndexPath *)indexPath
    
    https://developer.apple.com/library...stm/UICollectionView/indexPathForItemAtPoint:

    some snippet from an actual code I use in a UICollectionViewController

    Code:
    - (IBAction)handleLongPress:(id)sender
    
    {
       UILongPressGestureRecognizer *pg = (UILongPressGestureRecognizer *)sender;
       
       // find the location
       CGPoint point = [pg locationInView:self.collectionView];
    
       // get the path for the cell underneath the point   
       NSIndexPath *idxPath = [self.collectionView indexPathForItemAtPoint:point];
    
       // ... much more code
    }
    
    But keep in mind that with the "aggressive" (or let say: consistent) reuse of cells the value is mainly good for limited scope; means don't try to store the cell reference in own lists for reuse; store the indexPath instead.
     
  3. moonman239 thread starter macrumors 68000

    Joined:
    Mar 27, 2009
    #3
    Thank you!
     

Share This Page