UICollectionView使用方法(二)

上一篇简单介绍了一下UICollectionView的属性以及布局类的使用,这一篇我们写一个Demo,来自定义一个UICollectionViewFlowLayout的类,实现我们需要的UICollectionView效果:
首先,我们先创建一个UICollectionView,还是那几步,注册-重用:

 UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64) collectionViewLayout:flowLayout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    
    UINib *nib = [UINib nibWithNibName:@"HTIndustryCollectionCell"
                                bundle: [NSBundle mainBundle]];
    [_collectionView registerNib:nib forCellWithReuseIdentifier:@"HTIndustryCollectionCell"];
    
    //设置代理
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    [self.view addSubview:self.collectionView];

用Xib做的UICollectionViewCell,所以我们注册方法要使用

- (void)registerNib:(nullable UINib *)nib forCellWithReuseIdentifier:(NSString *)identifier;

cell上面有个ImageView。接着我们实现dataSource的方法:

#pragma mark cell的数量
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _dataArray.count;
}

#pragma mark cell的视图
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = @"HTIndustryCollectionCell";
    HTIndustryCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    
    NSInteger row = indexPath.row;
    
    cell.imageView.image = [UIImage imageNamed:[_dataArray objectAtIndex:row]];
    
    return cell;
}

#pragma mark cell的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    return CGSizeMake(WIDTH - 60, HEIGHT - 64 - 60 - 60);
}

#pragma mark cell的点击事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"点击图片%ld",(long)indexPath.row);
} 

好,我们现在需要做自己想要的一个流布局效果,那么我们就创建一个继承自UICollectionViewFlowLayout的类:

-(id)init{
    self = [super init];
    if (self) {
        _move_x = 0.0;
        self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        self.minimumLineSpacing = 20.0;
        self.sectionInset = UIEdgeInsetsMake(0,30, 0,30);
    }
    return self;
}

- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity
{
    proposedContentOffset.y = 0.0;
    if (_isPagingEnabled) {
        proposedContentOffset.x = [self PageMove:proposedContentOffset];
    }else{
        proposedContentOffset.x = [self SMove:proposedContentOffset velocity:velocity];
    }
    return proposedContentOffset;
}


-(CGFloat)PageMove:(CGPoint)proposedContentOffset{
    CGFloat set_x =  proposedContentOffset.x;
    
    if (set_x > _move_x) {
        _move_x += WIDTH - self.minimumLineSpacing * 2;
    }else if(set_x < _move_x){
        _move_x -= WIDTH - self.minimumLineSpacing * 2;
    }
    set_x = _move_x;
    return set_x;
}

-(CGFloat)SMove:(CGPoint)proposedContentOffset velocity :(CGPoint)velocity{
    
    CGFloat offSetAdjustment = MAXFLOAT;
    CGFloat horizontalCenter = (CGFloat) (proposedContentOffset.x + (self.collectionView.bounds.size.width / 2.0));
    
    CGRect targetRect = CGRectMake(proposedContentOffset.x, 0.0, self.collectionView.bounds.size.width, self.collectionView.bounds.size.height);
    
    NSArray *array = [self layoutAttributesForElementsInRect:targetRect];
    
    UICollectionViewLayoutAttributes *currentAttributes;
    
    for (UICollectionViewLayoutAttributes *layoutAttributes in array)
    {
        if(layoutAttributes.representedElementCategory == UICollectionElementCategoryCell)
        {
            CGFloat itemHorizontalCenter = layoutAttributes.center.x;
            if (ABS(itemHorizontalCenter - horizontalCenter) <  ABS(offSetAdjustment))
            {
                currentAttributes   = layoutAttributes;
                offSetAdjustment    = itemHorizontalCenter - horizontalCenter;
            }
        }
    }
    
    CGFloat nextOffset          = proposedContentOffset.x + offSetAdjustment;
    
    proposedContentOffset.x     = nextOffset;
    
    CGFloat deltaX              = proposedContentOffset.x - self.collectionView.contentOffset.x;
    CGFloat velX                = velocity.x;
    
    if(deltaX == 0.0 || velX == 0 || (velX >  0.0  &&  deltaX >  0.0) || (velX <  0.0 &&  deltaX <  0.0)) {
        
    } else if(velocity.x >  0.0) {
        for (UICollectionViewLayoutAttributes *layoutAttributes in array)
        {
            if(layoutAttributes.representedElementCategory == UICollectionElementCategoryCell)
            {
                CGFloat itemHorizontalCenter = layoutAttributes.center.x;
                if (itemHorizontalCenter >  proposedContentOffset.x) {
                    proposedContentOffset.x = nextOffset + (currentAttributes.frame.size.width / 2) + (layoutAttributes.frame.size.width / 2);
                    break;
                }
            }
        }
    } else if(velocity.x <=  0.0) {
        for (UICollectionViewLayoutAttributes *layoutAttributes in array)
        {
            if(layoutAttributes.representedElementCategory == UICollectionElementCategoryCell)
            {
                CGFloat itemHorizontalCenter = layoutAttributes.center.x;
                if (itemHorizontalCenter >  proposedContentOffset.x) {
                    proposedContentOffset.x = nextOffset - ((currentAttributes.frame.size.width / 2) + (layoutAttributes.frame.size.width / 2));
                    break;
                }
            }
        }
    }
    
    if (proposedContentOffset.x == -0.0) {
        proposedContentOffset.x = 0.0;
        
    }
    return proposedContentOffset.x;
    
}

-(void)setPagingEnabled:(BOOL)isPagingEnabled{
    _isPagingEnabled = isPagingEnabled;
}


static CGFloat const ActiveDistance = 350;
static CGFloat const ScaleFactor = 0.05;

-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSArray *array = [super layoutAttributesForElementsInRect:rect];
    CGRect visibleRect;
    visibleRect.origin = self.collectionView.contentOffset;
    visibleRect.size = self.collectionView.bounds.size;
    
    for (UICollectionViewLayoutAttributes* attributes in array) {
        CGFloat distance = CGRectGetMidX(visibleRect) - attributes.center.x;
        CGFloat normalizedDistance = distance / ActiveDistance;
        CGFloat zoom = 1 + ScaleFactor*(1 - ABS(normalizedDistance));
        attributes.transform3D = CATransform3DMakeScale(1.0, zoom, 1.0);
        attributes.zIndex = 1;
    }
    return array;
}

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

我们将创建UICollectionView时用到的flowLayout替换成我们自定义的,看看将出现一种什么效果

    HTIndustryFlowLayout *flowLayout=[[HTIndustryFlowLayout alloc] init];
    
    [flowLayout setPagingEnabled:YES];
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64) collectionViewLayout:flowLayout];

下面就是见证奇迹的时刻:

UICollectionView使用方法(二)_第1张图片
IMG_4721.jpg

你可能感兴趣的:(UICollectionView使用方法(二))