iOS使用UICollectionView实现横向滚动照片效果

所属分类: 软件编程 / IOS 阅读数: 1817
收藏 0 赞 0 分享

本文实例为大家分享了iOS使用UICollectionView实现横向滚动展示照片的具体代码,供大家参考,具体内容如下

这是Demo链接

效果图

思路

1. 界面搭建

界面的搭建十分简单,采用UICollectionView和自定义cell进行搭建即可。

// ViewController.m

// 下面使用到的宏和全局变量
#define ScreenW [UIScreen mainScreen].bounds.size.width
#define ScreenH [UIScreen mainScreen].bounds.size.height
static NSString *const cellID = @"cellID";

// 创建collectionView的代码
- (void)setupCollectionView
{
 // 使用系统自带的流布局(继承自UICollectionViewLayout)
 UICollectionViewFlowLayout *layout = ({
 UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
 // 每个cell的大小
 layout.itemSize   = CGSizeMake(180, 180);
 // 横向滚动
 layout.scrollDirection  = UICollectionViewScrollDirectionHorizontal;
 // cell间的间距
 layout.minimumLineSpacing  = 40;

 //第一个cell和最后一个cell居中显示(这里我的Demo里忘记改了我用的是160,最后微调数据cell的大小是180)
 CGFloat margin = (ScreenW - 180) * 0.5;
 layout.sectionInset  = UIEdgeInsetsMake(0, margin, 0, margin);

 layout;
 });

 // 使用UICollectionView必须设置UICollectionViewLayout属性
 UICollectionView *collectionView = ({
 UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
 collectionView.center  = self.view.center;
 collectionView.bounds  = CGRectMake(0, 0, ScreenW, 200);
 collectionView.backgroundColor = [UIColor brownColor];
 // 这里千万记得在interface哪里写<UICollectionViewDataSource>!!!
 collectionView.dataSource = self;
 [collectionView setShowsHorizontalScrollIndicator:NO];

 [self.view addSubview:collectionView];

 collectionView;
 });

 // 实现注册cell,其中PhotoCell是我自定义的cell,继承自UICollectionViewCell
 UINib *collectionNib = [UINib nibWithNibName:NSStringFromClass([PhotoCell class])
      bundle:nil];
 [collectionView registerNib:collectionNib
 forCellWithReuseIdentifier:cellID];
}

// UICollectionViewCellDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView
 numberOfItemsInSection:(NSInteger)section
{
 return 10;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
    cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
 PhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID 
    forIndexPath:indexPath];

 // 图片名是 0 ~ 9
 cell.imageName = [NSString stringWithFormat:@"%ld", (long)indexPath.row];

 return cell;
}
// 界面是一个xib文件,在cell里拖了个ImageView,约束上下左右都是10
// 图片名是数字 0 ~ 9

// PhotoCell.h
@property (nonatomic, strong) NSString *imageName;

// PhotoCell.m
@interface PhotoCell ()

@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@end

@implementation PhotoCell

- (void)awakeFromNib {
 [super awakeFromNib];
 // Initialization code
}

- (void)setImageName:(NSString *)imageName
{
 _imageName = imageName;

 self.imageView.image = [UIImage imageNamed:imageName];
}

到这里最基础的效果就实现完了,一组大小相等的图片cell。

2.大小变化已经居中效果实现

由于系统的UICollectionViewFlowLayout无法实现我想要的效果,因此我重写下该类中的某些方法。
在UICollectionViewLayout中有这样两句注释:

1. Methods in this class are meant to be overridden and will be called by its collection view to gather layout information.
在这个类中的方法意味着被重写(overridden),并且将要被它的 collection view 调用,用于收集布局信息

2. To get the truth on the current state of the collection view, call methods on UICollectionView rather than these.
要获取 collection view 的当前状态的真相,调用UICollectionView上的方法,而不是这些
其中有一点需要解释下,collectionView的bounds的x和y实际上就是collectionView的内容视图的 x和y。关于这点,请看我写的一篇博文的解释:iOS bounds学习笔记以及仿写UIScrollView的部分功能

// MyFlowLayout.h
#import <UIKit/UIKit.h>

// 注意!继承自UICollectionViewFlowLayout,因为它继承自UICollectionViewLayout。
@interface TWLayout : UICollectionViewFlowLayout

// MyFlowLayout.m
/**
 * The default implementation of this method returns NO. Subclasses can override it and return an appropriate value based on whether changes in the bounds of the collection view require changes to the layout of cells and supplementary views.
 此方法的默认实现返回NO。 子类可以覆盖它,并根据 collection view 的 bounds 中的更改是否需要更改 cells 和 supplementary views(补充视图) 的布局返回适当的值。

 * If the bounds of the collection view change and this method returns YES, the collection view invalidates the layout by calling the invalidateLayoutWithContext: method.
 如果 collection view 的 bounds 更改并且此方法返回YES,则 collection view 通过调用invalidateLayoutWithContext:方法使布局更新。

 @param newBounds The new bounds of the collection view.
 @return YES if the collection view requires a layout update or NO if the layout does not need to change.
 */
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
 return YES;
}


/**
 * Returns the layout attributes for all of the cells and views in the specified rectangle.
 返回指定矩形中所有cells和views的布局属性。

 @param rect * The rectangle (specified in the collection view's coordinate system) containing the target views.
  包含目标视图的矩形(在集合视图的坐标系中指定)。

 @return * An array of UICollectionViewLayoutAttributes objects representing the layout information for the cells and views. The default implementation returns nil.
  UICollectionViewLayoutAttributes对象数组,表示cell和view的布局信息。默认实现返回nil。
 */
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
 // 获取collectionView的宽带
 CGFloat collectionW = self.collectionView.bounds.size.width;

 // 获取布局属性数组
 NSArray<UICollectionViewLayoutAttributes *> *attrs = [super layoutAttributesForElementsInRect:self.collectionView.bounds];
 for (int i = 0; i < attrs.count; i++) {
 UICollectionViewLayoutAttributes *attr = attrs[i];

 //每个显示的cell距离中心距离
 CGFloat margin = fabs((attr.center.x - self.collectionView.contentOffset.x) - collectionW * 0.5);

 // 缩放比例:(margin / (collectionW * 0.5))得出的结论相当于 0 ~ 1。而我们需要它的缩放比例是 1 ~ 0.65,这样就是 (1 - 0)~(1 - 0.35)
 CGFloat scale = 1 - (margin / (collectionW * 0.5)) * 0.35;

 attr.transform = CGAffineTransformMakeScale(scale, scale);
 }

 return attrs;
}


/**
 * Returns the point at which to stop scrolling.
 * 关于这个方法,最终的偏移量,并不是由手指滑动过的偏移量决定的。如果手指滑动比较快,手指滑动过后,视图还会多滚动一段距离;如果手指滑动缓慢,手指滑到何处,就停到何处。

 @param proposedContentOffset 建议的点(在集合视图的内容视图的坐标空间中)用于可见内容的左上角。 这表示集合视图计算为在动画结束时最可能使用的值。
 @param velocity 沿着水平轴和垂直轴的当前滚动速度。 该值以每秒点数为单位。
 @return 要使用的内容偏移量。 此方法的默认实现返回proposedContentOffset参数中的值。
 */
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity
{
 // 获取collectionView的宽度
 CGFloat collectionW = self.collectionView.bounds.size.width;
 // 获取当前的内容偏移量
 CGPoint targetP = proposedContentOffset;

 // 获取显示cell的布局属性数组,横向滚动,所以只用考虑横向的x和width,纵向不用考虑
 NSArray *attrs = [super layoutAttributesForElementsInRect:CGRectMake(targetP.x, 0, collectionW, MAXFLOAT)];

 // 距离中心点最近的cell的间距(中间那个cell距离最近,值可正可负)
 CGFloat minSpacing = MAXFLOAT;
 for (UICollectionViewLayoutAttributes *attr in attrs) {
 // 距离中心点的偏移量
 CGFloat centerOffsetX = attr.center.x - targetP.x - collectionW * 0.5;
 // fabs():CGFloat绝对值
 if (fabs(centerOffsetX) < fabs(minSpacing)) {
  minSpacing = centerOffsetX;
 }
 }
 targetP.x += minSpacing;

 return targetP;
}

最后,记得把 UICollectionViewFlowLayout 改成你自定义的FlowLayout对象!!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

iOS开发笔记--详解UILabel的相关属性设置

这篇文章主要介绍了iOS开发笔记--详解UILabel的相关属性设置,对初学者具有一定的参考价值,有需要的可以了解一下。
收藏 0 赞 0 分享

iOS中获取系统相册中的图片实例

这篇文章主要介绍了iOS中获取系统相册中的图片实例,具有一定的参考价值没有需要的朋友可以了解一下。
收藏 0 赞 0 分享

iOS 检测网络状态的两种方法

一般有Reachability和AFNetworking监测两种方式,都是第三方的框架,下文逐一详细给大家讲解,感兴趣的朋友一起看看吧
收藏 0 赞 0 分享

IOS 性能优化中离屏渲染

本文主要介绍了IOS 性能优化中离屏渲染的资料,提供了几种方法讲解了优化,有需要的小伙伴可以参考下
收藏 0 赞 0 分享

iOS获取当前设备型号等信息(全)包含iPhone7和iPhone7P

这篇文章主要介绍了iOS获取当前设备型号设备信息的总结包含iPhone7和iPhone7P,包括ios7之前之后的获取方式,本文接的非常详细,具有参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

iOS实现爆炸的粒子效果示例代码

之前在网上看到了一个Android实现的爆炸效果,感觉非常不错,所以自己尝试用iOS来实现下效果,现在将实现的过程、原理以及遇到的问题分享给大家,有需要的朋友们可以参考借鉴,下面来一起看看吧。
收藏 0 赞 0 分享

iOS毕业设计之天气预报App

这篇文章主要为大家详细介绍了iOS毕业设计之天气预报App,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

iOS轻点、触摸和手势代码开发

这篇文章主要为大家详细介绍了iOS轻点、触摸和手势代码开发,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

iOS 实现多代理的方法及实例代码

这篇文章主要介绍了iOS 实现多代理的方法及实例代码的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

iOS文字渐变色效果的实现方法

在大家日常开发iOS的过程中,可能会遇到要实现文字渐变色的效果,这篇文章文章通过示例代码和详细的步骤介绍了如何利用iOS实现文字渐变色的效果,实现后的很不错,感兴趣的朋友们下面来一起看看吧。
收藏 0 赞 0 分享
查看更多