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

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

这是Demo链接

效果图

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

思路

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,margin);

  layout;
 });

 // 使用UICollectionView必须设置UICollectionViewLayout属性
 UICollectionView *collectionView = ({
  UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
  collectionView.center   = self.view.center;
  collectionView.bounds   = CGRectMake(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,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对象!!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple 最新软件的错误和性能问题。
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只有5%的概率会遇到选择运营商界面且部分必须连接到iTunes才可以激活
一般在接外包的时候, 通常第三方需要安装你的app进行测试(这时候你的app肯定是还没传到app store之前)。
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应用变灰了。那么接下来我们看一下Flutter是如何实现的。Flutter中实现整个App变为灰色在Flutter中实现整个App变为灰色是非常简单的,只需要在最外层的控件上包裹ColorFiltered,用法如下:ColorFiltered(颜色过滤器)看名字就知道是增加颜色滤镜效果的,ColorFiltered( colorFilter:ColorFilter.mode(Colors.grey, BlendMode.
flutter升级/版本切换
(1)在C++11标准时,open函数的文件路径可以传char指针也可以传string指针,而在C++98标准,open函数的文件路径只能传char指针;(2)open函数的第二个参数是打开文件的模式,从函数定义可以看出,如果调用open函数时省略mode模式参数,则默认按照可读可写(ios_base:in | ios_base::out)的方式打开;(3)打开文件时的mode的模式是从内存的角度来定义的,比如:in表示可读,就是从文件读数据往内存读写;out表示可写,就是把内存数据写到文件中;
文章目录方法一:分别将图片和文字置灰UIImage转成灰度图UIColor转成灰度颜色方法二:给App整体添加灰色滤镜参考App页面置灰,本质是将彩色图像转换为灰度图像,本文提供两种方法实现,一种是App整体置灰,一种是单个页面置灰,可结合具体的业务场景使用。方法一:分别将图片和文字置灰一般情况下,App页面的颜色深度是24bit,也就是RGB各8bit;如果算上Alpha通道的话就是32bit,RGBA(或者ARGB)各8bit。灰度图像的颜色深度是8bit,这8bit表示的颜色不是彩色,而是256
领导让调研下黑(灰)白化实现方案,自己调研了两天,根据网上资料,做下记录只是学习过程中的记录,还是写作者牛逼
让学前端不再害怕英语单词(二),通过本文,可以对css,js和es6的单词进行了在逻辑上和联想上的记忆,让初学者更快的上手前端代码
用Python送你一颗跳动的爱心
在uni-app项目中实现人脸识别,既使用uni-app中的live-pusher开启摄像头,创建直播推流。通过快照截取和压缩图片,以base64格式发往后端。
商户APP调用微信提供的SDK调用微信支付模块,商户APP会跳转到微信中完成支付,支付完后跳回到商户APP内,最后展示支付结果。CSDN前端领域优质创作者,资深前端开发工程师,专注前端开发,在CSDN总结工作中遇到的问题或者问题解决方法以及对新技术的分享,欢迎咨询交流,共同学习。),验证通过打开选择支付方式弹窗页面,选择微信支付或者支付宝支付;4.可取消支付,放弃支付会返回会员页面,页面提示支付取消;2.判断支付方式,如果是1,则是微信支付方式。1.判断是否在微信内支付,需要在微信外支付。
Mac命令行修改ipa并重新签名打包
首先在 iOS 设备中打开开发者模式。位于:设置 - 隐私&安全 - 开发者模式(需重启)
一 现象导入MBProgressHUD显示信息时,出现如下异常现象Undefined symbols for architecture x86_64: "_OBJC_CLASS_$_MBProgressHUD", referenced from: objc-class-ref in ViewController.old: symbol(s) not found for architecture x86_64clang: error: linker command failed wit
Profiles >> 加号添加 >> Distribution >> "App Store" >> 选择 2.1 创建的App ID >> 选择绑定 2.3 的发布证书(.cer)>> 输入描述文件名称 >> Generate 生成描述文件 >> Download。Certificates >> 加号添加 >> "App Store and Ad Hoc" >> “Choose File...” >> 选择上一步生成的证书请求文件 >> Continue >> Download。
今天有需求,要实现的功能大致如下:在安卓和ios端实现分享功能可以分享链接,图片,文字,视频,文件,等欢迎大佬多多来给萌新指正,欢迎大家来共同探讨。如果各位看官觉得文章有点点帮助,跪求各位给点个“一键三连”,谢啦~声明:本博文章若非特殊注明皆为原创原文链接。