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

所属分类: 软件编程 / IOS 阅读数: 1851
收藏 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 仿百度外卖-首页重力感应的实例

这篇文章主要介绍了iOS 仿百度外卖-首页重力感应的实例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。
收藏 0 赞 0 分享

iOS实现时间显示几分钟前,几小时前以及刚刚的方法示例

这篇文章主要介绍了如何利用iOS实现时间显示是在几小时前,几分钟前以及刚刚的格式,类似大家在qq空间和朋友圈微博看到的效果,文中给出了详细的示例代码,有需要的朋友们可以参考借鉴,下面来一起学习学习吧。
收藏 0 赞 0 分享

iOS 条码及二维码扫描(从相册中读取条形码/二维码)及扫码过程中遇到的坑

本文主要给大家介绍ios中从手机相册中读取条形码和二维码的问题及解决办法,需要的朋友参考下
收藏 0 赞 0 分享

IOS Cache设计详细介绍及简单示例

这篇文章主要介绍了IOS Cache设计详细介绍及简单示例的相关资料,Cache的目的是为了追求更高的速度体验,Cache的源头是两种数据读取方式在成本和性能上的差异,需要的朋友可以参考下
收藏 0 赞 0 分享

iOS本地动态生成验证码的方法

这篇文章主要介绍了iOS本地动态生成验证码的方法,非常不错,具有参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

iOS绘制3D饼图的实现方法

饼图常用于统计学模块。常见的一般为2D饼图,这篇文章主要介绍了iOS绘制3D饼图的实现方法,3D饼图更加立体,用户的好感度也比较高,下面需要的朋友可以参考借鉴,一起来看看吧。
收藏 0 赞 0 分享

谈谈iOS开发之JSON格式数据的生成与解析

JSON格式取代了xml给网络传输带来了很大的便利,本篇文章主要介绍了iOS开发:对象直接转化成JSON详解,具有一定的参考价值,有兴趣的可以了解一下。
收藏 0 赞 0 分享

IOS 身份证校验详细介绍及示例代码

这篇文章主要介绍了IOS 身份证校验详细介绍及示例代码的相关资料,这里对身份校验比较详细,附有简单实例,需要的朋友可以参考下
收藏 0 赞 0 分享

IOS 自定义UICollectionView的头视图或者尾视图UICollectionReusableView

这篇文章主要介绍了IOS 自定义UICollectionView的头视图或者尾视图UICollectionReusableView的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

IOS 仿支付宝支付屏幕亮度变化机制

这篇文章主要介绍了IOS 仿支付宝支付屏幕亮度变化机制的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多