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

所属分类: 软件编程 / IOS 阅读数: 1808
收藏 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 服务器端推送证书生成的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

浅谈iOS推送证书生成pem文件(详细生成过程)

这篇文章主要介绍了浅谈iOS推送证书生成pem文件(详细生成过程),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

iOS高仿微信文章悬浮球功能

这篇文章主要介绍了iOS高仿微信文章悬浮球功能,本文给大家介绍的非常详细,具有一定的参考解决价值,需要的朋友可以参考下
收藏 0 赞 0 分享

通过一行代码搞定UITextField的输入格式限制

这篇文章主要给大家介绍了如何通过一行代码搞定UITextField的输入格式限制的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

iOS判断是否越狱设备方法示例

这篇文章主要给大家介绍了关于iOS判断是否越狱设备的相关资料,文中通过示例代码介绍的非常详细,对各位iOS开发者们具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

iOS开发教程之Status Bar状态栏设置的方法汇总

iOS 的 Status Bar 状态栏是一个比较坑的地方,所以下面这篇文章主要给大家介绍了关于iOS开发教程之Status Bar状态栏设置的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考下
收藏 0 赞 0 分享

iOS开发之导航栏各种右滑返回失效的解决方法汇总

这篇文章主要给大家总结介绍了关于iOS开发教程之导航栏各种右滑返回失效的解决方法,文中通过示例代码介绍的非常详细,对各位iOS具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

iOS实现简单的头部缩放功能

这篇文章主要介绍了iOS 简单的头部缩放效果,头部伴随模糊效果放大缩小,并在一定位置时悬停充当导航栏,本文给大家提供实现思路,需要的朋友可以参考下
收藏 0 赞 0 分享

iOS中震动反馈(UIFeedbackGenerator)与系统震动详解

最近要做一个项目,需要持续响铃并振动,所以就有了这篇文章,下面这篇文章主要给大家介绍了关于iOS中震动反馈(UIFeedbackGenerator)与系统震动的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多