现在的位置: 首页 > 编程语言 > 正文

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

2020年02月18日 编程语言 ⁄ 共 6180字 ⁄ 字号 评论关闭

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

这是Demo链接

效果图

思路

1. 界面搭建

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

// ViewController.m// 下面使用到的宏和全局变量#define ScreenW [UIScreen mainScreen].bounds.size.width#define ScreenH [UIScreen mainScreen].bounds.size.heightstatic 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使用UICollectionView实现横向滚动照片效果的相关介绍,要了解更多ios, uicollectionview, 横向滚动内容请登录学步园。

抱歉!评论已关闭.