[iOS] UICollectionView實現圖片水平滾動

先簡單看一下效果:

result

準備數據

首先先加入一些資源文件:app

先創建一個xcassets文件,放入圖片:ide

xcassets

再創建一個plist文件,寫入與圖片對應的內容:佈局

plist

在ViewController中讀取plist到詞典中:post

@property (nonatomic, strong) NSArray *itemTitles;

NSString *path = [[NSBundle mainBundle] pathForResource:@"titles" ofType:@"plist"];
NSDictionary *rootDictionary = [[NSDictionary alloc] initWithContentsOfFile:path];
self.itemTitles = [rootDictionary objectForKey:@"heros"];

能夠打log輸出,能夠看到plist的內容已經讀取出來,後面就能夠用_itemTitle做爲數據源了。優化

添加UICollectionView初步顯示圖片

每一個CollectionView都有一個對應的佈局layout,對於默認的的UICollectionViewFlowLayout,效果是相似Android的GridView的佈局。若是要自定義CollectionView的樣式,就要對這個layout進行修改。ui

創建本身的HorizontalFlowLayout,繼承自UICollectionViewFlowLayout,而後在初始化方法裏將滾動方向設置爲水平:atom

- (instancetype) init {
if (self = [super init]) {
self.scrollDirection = UICollectionViewScrollDirectionHorizontal;

}
return self;
}

接下來定製咱們的cell的顯示樣式,創建DotaCell,繼承自UICollectionViewCell。因爲咱們要實現的是圖片和文字的上下佈局,因此增長兩個屬性:spa

@interface DotaCell : UICollectionViewCell

@property (nonatomic, strong) UIImageView *image;
@property (nonatomic, strong) UILabel *name;

@end

而後設置圖片與文字上下對齊佈局,這裏我使用pod導入Masonry庫來寫自動佈局:代理


- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self initialize];
}
return self;
}

- (void)initialize {
self.layer.doubleSided = NO;

self.image = [[UIImageView alloc] init];
self.image.backgroundColor = [UIColor clearColor];
self.image.contentMode = UIViewContentModeCenter;
self.image.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

self.name = [[UILabel alloc] init];
self.name.font = [UIFont fontWithName:@"Helvetica Neue" size:20];
self.name.textAlignment = NSTextAlignmentCenter;

[self.contentView addSubview:self.image];
[self.contentView addSubview:self.name];

[_image mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.right.equalTo(self.contentView);
make.top.equalTo(self.contentView).offset(30);
make.bottom.equalTo(_name.mas_top).offset(-10);
}];

[_name mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.right.equalTo(self.contentView);
make.top.equalTo(_image.mas_bottom).offset(10);
make.bottom.equalTo(self.contentView).offset(-20);
}];
}

 

寫好layoutcell後就能夠用這兩個類來初始化咱們的collectionView了:code

//add in view did load
self.layout = [[HorizontalFlowLayout alloc] init];

CGRect rct = self.view.bounds;
rct.size.height = 150;
rct.origin.y = [[UIScreen mainScreen] bounds].size.height / 2.0 - rct.size.height;

self.collectionView = [[UICollectionView alloc] initWithFrame:rct collectionViewLayout:_layout];
self.collectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
self.collectionView.showsHorizontalScrollIndicator = NO;
self.collectionView.decelerationRate = UIScrollViewDecelerationRateNormal;

[self.collectionView registerClass:[DotaCell class] forCellWithReuseIdentifier:NSStringFromClass([DotaCell class])];
[self.collectionView setBackgroundColor:[UIColor clearColor]];
[self.collectionView setDelegate:self];
[self.collectionView setDataSource:self];

[self.view addSubview:_collectionView];

添加UICollectionViewDataSource的代理方法,使其顯示數據。


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return [self.itemTitles count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
DotaCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([DotaCell class]) forIndexPath:indexPath];

cell.image.image = [UIImage imageNamed:[self.itemTitles objectAtIndex:indexPath.row]];
cell.name.text = [self.itemTitles objectAtIndex:indexPath.row];

return cell;
}

這樣程序就有了咱們想要的初步效果:
gif1

圖片水平排放

但…效果的確不好!
下面要作的就是逐步完善效果,首先咱們要讓兩排圖像變成一排去展現。那要怎麼去作?首先,咱們在初始化collectionView的地方設置了高度爲150,因此圖片就擠在這個150的高度裏儘量的壓縮顯示。因爲collectionView的尺寸已經設定,那麼就剩cell的尺寸能夠控制了。實現CollectionViewFlowLayoutDelegate的代理方法sizeForItemAtIndexPath


- (CGSize)collectionView:(nonnull UICollectionView *)collectionView layout:(nonnull UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
return CGSizeMake(64, collectionView.bounds.size.height);
}

這裏寬度64是圖片的尺寸,高度設置填滿collectionView的高度是爲了防止上圖中兩行圖片擠壓的狀況,因此直接讓一個cell的高度佔滿整個容器。

這時候的效果好了不少,已經有點樣子了:
gif2

頂端圖片滑到中間

但這離咱們最終的效果還差很遠,接下來我須要實現讓第一張圖片和最後一張圖片都能滑到屏幕中點的位置,這應該是很常見的效果,實現起來也很簡單。首先咱們的一排cell都默認爲頂端與collectionView的兩端對齊的,collectionView的左右兩端與viewController.view也是對齊的,因此顯示的效果是,兩端的圖片都與屏幕對齊。知道這個關係就好辦了,直接設置collectionView與其父view的內間距便可。
依舊是實現flowLayout的代理方法:


//Asks the delegate for the margins to apply to content in the specified section.安排初始位置
//使先後項都能居中顯示
- (UIEdgeInsets)collectionView:(nonnull UICollectionView *)collectionView layout:(nonnull UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {

NSInteger itemCount = [self collectionView:collectionView numberOfItemsInSection:section];

NSIndexPath *firstIndexPath = [NSIndexPath indexPathForItem:0 inSection:section];
CGSize firstSize = [self collectionView:collectionView layout:collectionViewLayout sizeForItemAtIndexPath:firstIndexPath];

NSIndexPath *lastIndexPath = [NSIndexPath indexPathForItem:itemCount - 1 inSection:section];
CGSize lastSize = [self collectionView:collectionView layout:collectionViewLayout sizeForItemAtIndexPath:lastIndexPath];

return UIEdgeInsetsMake(0, (collectionView.bounds.size.width - firstSize.width) / 2,
0, (collectionView.bounds.size.width - lastSize.width) / 2);


}

效果如圖:
gif3

居中圖片放大顯示

接下來添加一個咱們須要的特效,就是中間的圖片放大顯示,其他的縮小而且增長一層半透明效果。
FlowLayout中有一個名爲layoutAttributesForElementsInRect的方法,功能如其名,就是設置範圍內元素的layout屬性。對於這個效果,首先須要設置放大的比例,其次要根據圖片大小和間距來設定一個合適的觸發放大的區域寬度,當圖滑入這個區域就進行縮放。


static CGFloat const ActiveDistance = 80;
static CGFloat const ScaleFactor = 0.2;
//這裏設置放大範圍
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{

NSArray *array = [super layoutAttributesForElementsInRect:rect];

CGRect visibleRect = (CGRect){self.collectionView.contentOffset, self.collectionView.bounds.size};

for (UICollectionViewLayoutAttributes *attributes in array) {
//若是cell在屏幕上則進行縮放
if (CGRectIntersectsRect(attributes.frame, rect)) {

attributes.alpha = 0.5;

CGFloat distance = CGRectGetMidX(visibleRect) - attributes.center.x;//距離中點的距離
CGFloat normalizedDistance = distance / ActiveDistance;

if (ABS(distance) < ActiveDistance) {
CGFloat zoom = 1 + ScaleFactor * (1 - ABS(normalizedDistance)); //放大漸變
attributes.transform3D = CATransform3DMakeScale(zoom, zoom, 1.0);
attributes.zIndex = 1;
attributes.alpha = 1.0;
}
}
}

return array;
}

效果以下:
gif4

滑動校訂

這時候幾乎完成了,但還差點東西,就是讓其在滾動中止的時候,離屏幕中間最近的cell自動矯正位置到中間。仍是在FlowLayout添加該方法,具體說明我都寫到註釋裏了:


//scroll 中止對中間位置進行偏移量校訂
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity {
CGFloat offsetAdjustment = MAXFLOAT;
//// |-------[-------]-------|
//// |滑動偏移|可視區域 |剩餘區域|
//是整個collectionView在滑動偏移後的當前可見區域的中點
CGFloat centerX = proposedContentOffset.x + (CGRectGetWidth(self.collectionView.bounds) / 2.0);
// CGFloat centerX = self.collectionView.center.x; //這個中點始終是屏幕中點
//因此這裏對collectionView的具體尺寸不太理解,輸出的是屏幕大小,但實際上寬度確定超出屏幕的

CGRect targetRect = CGRectMake(proposedContentOffset.x, 0.0, self.collectionView.bounds.size.width, self.collectionView.bounds.size.height);

NSArray *array = [super layoutAttributesForElementsInRect:targetRect];

for (UICollectionViewLayoutAttributes *layoutAttr in array) {
CGFloat itemCenterX = layoutAttr.center.x;

if (ABS(itemCenterX - centerX) < ABS(offsetAdjustment)) { // 找出最小的offset 也就是最中間的item 偏移量
offsetAdjustment = itemCenterX - centerX;
}
}

return CGPointMake(proposedContentOffset.x + offsetAdjustment, proposedContentOffset.y);
}

gif5

增長圖片點擊效果

最後 添加一個點擊cell 將其滾動到中間
viewcontroller添加CollectionViewDelegate的代理方法

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
[self.collectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone];

//滾動到中間
[self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
}

 

gif6

封裝成控件

當咱們把效果實現以後,就能夠考慮將代碼優化一下,合到一個類裏,減小書寫常量,增長接口,封裝成一個控件去使用。好比能夠設定文字的顯示與隱藏接口,再好比增長適應各類尺寸的圖片等等。這個代碼就不放了,畢竟不難,有問題給我留言好了。

相關文章
相關標籤/搜索