zoukankan      html  css  js  c++  java
  • 使用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

  • 相关阅读:
    使用RazorGenerator对视图View进行单元测试
    C#常用获取本周、本月、本季度、本年的时间起止段代码
    Redis使用记录
    Git和ConEmu
    mongodb单索引的升序和降序
    AES 加密解密 php c#
    redis 外网连接错误
    .net mvc 分页
    检查Windows上安装的.net版本
    sqlserver跨服务器查询
  • 原文地址:https://www.cnblogs.com/bug-sniper/p/5249470.html
Copyright © 2011-2022 走看看