iOS 彈簧效果(CollectionView實現(xiàn))

這個是我根據@allsome 大神的印象筆記彈簧效果那篇改成oc的,因為大神之前是swift寫的 我看到底下的評論說有的用oc寫的稍微有點問題,所以我就想根據大神的方法 用oc寫出來 可以大家一起分享

spring.gif

我們先了解三個概念
**contentSize: **The size of the content view. 其實就是scrollview可以滾動的區(qū)域,比如frame = (0 ,0 ,320 ,480) contentSize = (320 ,960),代表你的scrollview可以上下滾動,滾動區(qū)域為frame大小的兩倍。
contentOffset:The point at which the origin of the content view is offset from the origin of the scroll view. 是scrollview當前顯示區(qū)域頂點相對于frame頂點的偏移量,比如上個例子你拉到最下面,contentoffset就是(0 ,480),也就是y偏移了480
contentInset:The distance that the content view is inset from the enclosing scroll view.是scrollview的contentview的頂點相對于scrollview的位置,例如你的contentInset = (0 ,100),那么你的contentview就是從scrollview的(0 ,100)開始顯示

其實主要的思想是UICollectionViewFlowLayout里的這兩個方法

//當邊界發(fā)生改變時,是否應該刷新布局。如果YES則在邊界變化(一般是scroll到其他地方)時,將重新計算需要的布局信息。
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
    return YES;
}

//返回rect中的所有的元素的布局屬性
//返回的是包含UICollectionViewLayoutAttributes的NSArray
- (NSArray*)layoutAttributesForElementsInRect:(CGRect)rect {
    float offsetY = self.collectionView.contentOffset.y;
    NSArray * attrsArray = [super layoutAttributesForElementsInRect:rect];
    //collectionView的
    float collectionViewFrameHeight = self.collectionView.frame.size.height;
    float collectionViewContentHeight = self.collectionView.contentSize.height;
    float ScrollViewContentInsetBottom = self.collectionView.contentInset.bottom;
    float bottomOffset = offsetY + collectionViewFrameHeight - collectionViewContentHeight - ScrollViewContentInsetBottom;
//    float numOfItems = self.collectionView.numberOfSections;
    for (_attr in attrsArray) {
        if ([_attr representedElementCategory] == UICollectionElementCategoryCell) {
            CGRect cellRect = _attr.frame;
            if (offsetY <= 0) {
                float distance = fabs(offsetY) / 10.0;
                cellRect.origin.y += offsetY + distance * (CGFloat)(_attr.indexPath.row + 1);
            }else if(bottomOffset > 0) {
                float distance = bottomOffset / 10.0;
                cellRect.origin.y += bottomOffset - distance *
                (CGFloat)( _attr.indexPath.row);
            }
            _attr.frame = cellRect;
        }
    }
    return attrsArray;
}

我寫的demo在GitHub上 這個demo里的
地址:https://github.com/942334790/synthesizeDemo

1.png

這幾個類是關于 彈簧效果的

這里邊還有TextView 添加placeholder的
還有第三方SDCycleScrollView的輪播效果的
大家可以一起看一下

如果有什么不對的地方歡迎大家告訴我
我還是希望在iOS這條道路上 我能堅持一直走下去

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容