使用uicollectionview 实现单元格滑动吸附效果

项目中遇到的需求,需要作出每个单元格必须完全显示.

使用uicolectionview可以实现:

collectionview的布局全部由UICollectionViewFlowLayout控制.

UICollectionViewFlowLayout的一个方法控制滑动结束单元格的停止位置:

-(CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity

 

所以必须重写这个方法:

.h文件

#import <UIKit/UIKit.h> 

@interface Customlayout : UICollectionViewFlowLayout 

@end

 

.m文件

#import "Customlayout.h" 

@implementation Customlayout 

-(CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity

{

    //1.计算scrollview最后停留的范围

    CGRect lastRect ;

    lastRect.origin = proposedContentOffset;

    lastRect.size = self.collectionView.frame.size;    

    //2.取出这个范围内的所有属性

    NSArray *array = [self layoutAttributesForElementsInRect:lastRect];    

    //起始的x值,也即默认情况下要停下来的x

    CGFloat startX = proposedContentOffset.x;

    

    //3.遍历所有的属性

    CGFloat adjustOffsetX = MAXFLOAT;

    for (UICollectionViewLayoutAttributes *attrs in array) {

        CGFloat attrsX = CGRectGetMinX(attrs.frame); //单元格x

        CGFloat attrsW = CGRectGetWidth(attrs.frame) ; //单元格宽度

        

        if (startX - attrsX  < attrsW/2) { //小于一半

            adjustOffsetX = -(startX - attrsX);

        }else{

            adjustOffsetX = attrsW - (startX - attrsX);

        }

        

        break ;//只循环数组中第一个元素即可,所以直接break

    }

    return CGPointMake(proposedContentOffset.x + adjustOffsetX, proposedContentOffset.y);

} 

@end

 

转载于:https://www.cnblogs.com/bug-sniper/p/5249470.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值