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

  • 相关阅读:
    475. Heaters
    69. Sqrt(x)
    83. Remove Duplicates from Sorted List Java solutions
    206. Reverse Linked List java solutions
    100. Same Tree Java Solutions
    1. Two Sum Java Solutions
    9. Palindrome Number Java Solutions
    112. Path Sum Java Solutin
    190. Reverse Bits Java Solutin
    202. Happy Number Java Solutin
  • 原文地址:https://www.cnblogs.com/bug-sniper/p/5249470.html
Copyright © 2011-2022 走看看