2016-08-04 2 views
2

Я работаю с коллекционным просмотром, который скользит по горизонтали и пытается выполнить пользовательский макет ячеек, аналогичный «ближе к iphone». Я понятия не имею, как добиться такого эффекта, или с чего начать, поэтому я надеялся получить некоторые указатели. Я очень плохо объясняю себя, поэтому я попытался показать желаемый эффект от того, как он себя ведет сейчас, до того, как он должен себя вести.Collectionview custom layout layout/behavior

Заранее благодарен!

enter image description here

+1

Я думаю, вы должны увидеть пример, показанный здесь https://github.com/nicklockwood/iCarousel Здесь вы найдете множество типов эффектов, тогда вы получите по крайней мере знаю, как начать и что делать –

+0

спасибо много! Это похоже на совершенно правильный механизм для пользовательского эффекта. – Imbue

ответ

3

Я работал с подобной точки зрения, как this.This является GitHub link моего проекта. This is the screenshot of the view Единственное различие между вашим требованием и моим представлением - вам нужно также увеличить левую ячейку. Чтобы достичь этой точки зрения, я столкнулся с двумя серьезными проблемами:

1) Остановить прокрутку точно, когда две ячейки (левая ячейка и правая ячейка) одинаково открыты, для этого я включил следующий код в мой файл CollectionView.m.

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset 
{ 
    float pageWidth = 240; // width + space 

    float currentOffset = scrollView.contentOffset.x; 
    float targetOffset = targetContentOffset->x; 
    float newTargetOffset = 0; 

    if (targetOffset > currentOffset) 
     newTargetOffset = ceilf(currentOffset/pageWidth) * pageWidth; 
    else 
     newTargetOffset = floorf(currentOffset/pageWidth) * pageWidth; 

    if (newTargetOffset < 0) 
     newTargetOffset = 0; 
    else if (newTargetOffset > scrollView.contentSize.width) 
     newTargetOffset = scrollView.contentSize.width; 

    targetContentOffset->x = currentOffset; 
    [scrollView setContentOffset:CGPointMake(newTargetOffset, 0) animated:YES]; 

    int index = newTargetOffset/pageWidth; 

    if (index == 0) { // If first index 
     CollectionViewCell *cell =(CollectionViewCell *) [self cellForItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0]]; 
     cell.transform = CGAffineTransformIdentity; 
     cell = (CollectionViewCell *)[self cellForItemAtIndexPath:[NSIndexPath indexPathForItem:index + 1 inSection:0]]; 
     //cell.transform = TRANSFORM_CELL_VALUE; 

    }else{ 
     CollectionViewCell *cell =(CollectionViewCell *)[self cellForItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0]]; 
     //cell.transform = CGAffineTransformIdentity; 

     index --; // left 
     cell =(CollectionViewCell *)[self cellForItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0]]; 
      // cell.transform = TRANSFORM_CELL_VALUE; 
     index ++; 
     index ++; // right 
     cell = (CollectionViewCell *)[self cellForItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0]]; 
     //cell.transform = TRANSFORM_CELL_VALUE; 
    } 
} 

2) Во-вторых вы должны обеспечить надлежащее ограничение в клетку, чтобы достичь требования, для этого я использовал UICollectionViewFlowLayout класса. В этом я предоставляю правильное ограничение видимым клеткам. FlowLayout код выглядит следующим образом:

#import "CollectionLayout.h" 


@implementation CollectionLayout 
{ 
    NSIndexPath *mainIndexPath; 
} 

-(void)prepareLayout{ 
    [super prepareLayout]; 
} 

-(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath{ 
    UICollectionViewLayoutAttributes *attributes = [[super layoutAttributesForItemAtIndexPath:indexPath] copy]; 
    CATransform3D theTransform = CATransform3DIdentity; 
    const CGFloat theScale = 1.05f; 
    theTransform = CATransform3DScale(theTransform, theScale, theScale, 1.0f); 
    attributes.transform3D=theTransform; 
    return attributes; 
} 

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds { 
    return YES; 
} 

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect{ 
    NSArray *attributesSuper = [super layoutAttributesForElementsInRect:rect]; 
    NSArray *attributes = [[NSArray alloc]initWithArray:attributesSuper copyItems:YES]; 
    NSArray *cellIndices = [self.collectionView indexPathsForVisibleItems]; 
    NSIndexPath *neededIndexPath = [NSIndexPath indexPathForRow:0 inSection:0]; 
    for(NSInteger i=0;i<cellIndices.count;i++){ 
     NSIndexPath *indexPath = [cellIndices objectAtIndex:i]; 
     if(indexPath.row>neededIndexPath.row){ 
      neededIndexPath=indexPath; 
     } 
     NSLog(@"%ld,%ld",(long)indexPath.row,(long)indexPath.section); 
    } 
    if(cellIndices.count==0){ 
     mainIndexPath = [NSIndexPath indexPathForRow:0 inSection:0]; 
    }else{ 
     if(neededIndexPath.row>0) 
      mainIndexPath = [NSIndexPath indexPathForRow:neededIndexPath.row-1 inSection:0]; 
    } 

    for (UICollectionViewLayoutAttributes *attribute in attributes) 
    { 
     [self applyTransformToLayoutAttributes:attribute]; 
    } 
    return attributes; 
} 

-(void) applyTransformToLayoutAttributes:(UICollectionViewLayoutAttributes *)attribute{ 
    if(attribute.indexPath.row == mainIndexPath.row){ 
     attribute.size = CGSizeMake(self.collectionView.bounds.size.width-40, self.collectionView.bounds.size.height); 
     attribute.zIndex+=10; 
    } 
} 

#pragma mark - Transform related 

@end 

После того, как вы клонировать проект с моей GitHub ссылки, вы легко поймете, что я сделал, и вы можете написать свой собственный код для достижения вашей view.You нужна будет только предоставить ваш ограничение в этой части кода. Вам также необходимо правильно настроить zIndex для каждой ячейки.

-(void) applyTransformToLayoutAttributes:(UICollectionViewLayoutAttributes *)attribute{ 
     if(attribute.indexPath.row == mainIndexPath.row){ 
      attribute.size = CGSizeMake(self.collectionView.bounds.size.width-40, self.collectionView.bounds.size.height); 
      attribute.zIndex+=10; 
     } 
    } 

Надеюсь, вы поняли мою точку зрения.

примечание: я тестировал код github только на iPhone 5s, вам может потребоваться немного настроить другие устройства.

+0

Спасибо большое! Это было отличное вдохновение, и мне удалось сделать свой собственный вариант, который работал точно так, как ожидалось. Это отличная работа! – Imbue