這個是我根據(jù)@allsome 大神的印象筆記彈簧效果那篇改成oc的,因為大神之前是swift寫的 我看到底下的評論說有的用oc寫的稍微有點問題,所以我就想根據(jù)大神的方法 用oc寫出來 可以大家一起分享
我們先了解三個概念
**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
這幾個類是關(guān)于 彈簧效果的
這里邊還有TextView 添加placeholder的
還有第三方SDCycleScrollView的輪播效果的
大家可以一起看一下
如果有什么不對的地方歡迎大家告訴我
我還是希望在iOS這條道路上 我能堅持一直走下去