You can achieve this effect independently of having a custom layout.
The animation code should go inside collectionView:cellForItemAtIndexPath:
When a cell is dequeued, its frame
will be set to what is specified in your layout. You can store it in a temporary variable as the final frame
for the cell. You can then set the cell.frame
to a initial position outside the screen, and then animate towards the desired final position. Something along the lines of:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionView *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
CGRect finalCellFrame = cell.frame;
//check the scrolling direction to verify from which side of the screen the cell should come.
CGPoint translation = [collectionView.panGestureRecognizer translationInView:collectionView.superview];
if (translation.x > 0) {
cell.frame = CGRectMake(finalCellFrame.origin.x - 1000, - 500.0f, 0, 0);
} else {
cell.frame = CGRectMake(finalCellFrame.origin.x + 1000, - 500.0f, 0, 0);
}
[UIView animateWithDuration:0.5f animations:^(void){
cell.frame = finalCellFrame;
}];
return cell;
}
The code above will animate cells on a horizontal UICollectionView
, coming from the top of the screen, and from either side, depending on the scrolling direction. You could also check the current indexPath
to have cells animating from different positions on more complicated layouts, as well as animate other properties along with the frame, or apply a transform.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…