ios uicollection viewは横スクロールを実現します。


今はカードの効果を使うアプリが多く、前の会社がカードの効果を実現させるために、カードの実現に関する文章を書きました。文章の最後にデモがついています。
実際にUICCollection Viewを使うことを選びました。UICCollection View Flow Layoutでスタイルをカスタマイズします。具体的な実現を見てみます。
効果

実際にUICCollection Viewを使うことを選びました。UICCollection View Flow Layoutでスタイルをカスタマイズします。具体的な実現を見てみます。
具体的に実現する
1、ViView Controller.mコード実現

#import "ViewController.h"
#import "CollModel.h"
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
#define SCREEN_RATE ([UIScreen mainScreen].bounds.size.width/375.0)
#import "imageCell.h"
#import "LHHorizontalPageFlowlayout.h"
static NSString * const imageC = @"imageCell";
static NSString * const moreImageC = @"imageCell";
static const NSInteger kItemCountPerRow = 5; //    5 
static const NSInteger kRowCount = 3; //      
static float imageHeight = 80;//cell   
@interface ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic, strong) UICollectionView * collectionView;
@property (nonatomic, strong) NSMutableArray * modelArray;
@property (nonatomic, strong) UICollectionView * moreCollectionView;
@end
@implementation ViewController
- (void)viewDidLoad {
 [super viewDidLoad];
 NSArray *appArray = [[self getDict] objectForKey:@"dictInfo"];
 for (int i = 0; i < appArray.count; i++) {
  NSDictionary * appDic = appArray[i];
  CollModel * model = [[CollModel alloc]init];
  model.title = [appDic objectForKey:@"title"];
  model.url = [appDic objectForKey:@"url"];
  [self.modelArray addObject:model];
 }
 [self createCollectionView];
 [self createRightCollectionView];
}

- (NSDictionary *)getDict {
 NSString * string = @"{\"dictInfo\":[{\"title\":\"   \",\"url\":\"1.jpeg\"},{\"title\":\"   \",\"url\":\"2.jpeg\"},{\"title\":\"   \",\"url\":\"3.jpeg\"},{\"title\":\"   \",\"url\":\"4.jpeg\"},{\"title\":\"   \",\"url\":\"5.jpeg\"},{\"title\":\"   \",\"url\":\"6.jpeg\"},{\"title\":\"   \",\"url\":\"7.jpeg\"},{\"title\":\"   \",\"url\":\"1.jpeg\"},{\"title\":\"   \",\"url\":\"2.jpeg\"},{\"title\":\"   \",\"url\":\"3.jpeg\"},{\"title\":\"   \",\"url\":\"4.jpeg\"},{\"title\":\"   \",\"url\":\"5.jpeg\"},{\"title\":\"   \",\"url\":\"6.jpeg\"},{\"title\":\"   \",\"url\":\"7.jpeg\"},{\"title\":\"   \",\"url\":\"1.jpeg\"},{\"title\":\"   \",\"url\":\"2.jpeg\"},{\"title\":\"   \",\"url\":\"3.jpeg\"},{\"title\":\"   \",\"url\":\"4.jpeg\"},{\"title\":\"   \",\"url\":\"5.jpeg\"},{\"title\":\"   \",\"url\":\"6.jpeg\"},{\"title\":\"   \",\"url\":\"7.jpeg\"}]}";
 NSDictionary *infoDic = [self dictionaryWithJsonString:string];
 return infoDic;
}


-(NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
 if (jsonString == nil) {
  return nil;
 }
 NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
 NSError *err;
 NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
 if(err)
 {
  NSLog(@"json    :%@",err);
  return nil;
 }
 return dic;
}

- (NSMutableArray *)modelArray {
 if (!_modelArray) {
  _modelArray = [NSMutableArray array];
 }
 return _modelArray;
}

- (void)createCollectionView{
 UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
 layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
 layout.minimumLineSpacing = 0;
 layout.minimumInteritemSpacing = 0;
 _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 100, [UIScreen mainScreen].bounds.size.width, imageHeight * SCREEN_RATE) collectionViewLayout:layout];
 _collectionView.tag = 11;
 _collectionView.backgroundColor = [UIColor colorWithRed:186 / 255.0 green:186 / 255.0 blue:186 / 255.0 alpha:0.9];
 _collectionView.dataSource = self;
 _collectionView.delegate = self;
 _collectionView.bounces = NO;
 _collectionView.alwaysBounceHorizontal = YES;
 _collectionView.alwaysBounceVertical = NO;
 _collectionView.showsHorizontalScrollIndicator = NO;
 _collectionView.showsVerticalScrollIndicator = NO;
 [self.view addSubview:_collectionView];
 [_collectionView registerClass:[imageCell class] forCellWithReuseIdentifier:imageC];
}

- (void)createRightCollectionView{
 
 LHHorizontalPageFlowlayout * layout = [[LHHorizontalPageFlowlayout alloc] initWithRowCount:kRowCount itemCountPerRow:kItemCountPerRow];
 [layout setColumnSpacing:0 rowSpacing:0 edgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
 layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
 // UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
 // layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
 layout.minimumLineSpacing = 0;
 layout.minimumInteritemSpacing = 0;
 _moreCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 300, [UIScreen mainScreen].bounds.size.width, imageHeight * SCREEN_RATE * kRowCount) collectionViewLayout:layout];
 _moreCollectionView.backgroundColor = [UIColor clearColor];
 _moreCollectionView.tag = 22;
 _moreCollectionView.dataSource = self;
 _moreCollectionView.delegate = self;
 _moreCollectionView.bounces = NO;
 _moreCollectionView.alwaysBounceHorizontal = YES;
 _moreCollectionView.alwaysBounceVertical = NO;
 _moreCollectionView.backgroundColor = [UIColor colorWithRed:186 / 255.0 green:186 / 255.0 blue:186 / 255.0 alpha:0.9];
 _moreCollectionView.showsHorizontalScrollIndicator = NO;
 _moreCollectionView.showsVerticalScrollIndicator = NO;
 [self.view addSubview:_moreCollectionView];
 [_moreCollectionView registerClass:[imageCell class] forCellWithReuseIdentifier:moreImageC];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
 return self.modelArray.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
 CollModel * model = self.modelArray[indexPath.row];
 imageCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:imageC forIndexPath:indexPath];
 cell.itemModel = model;
 return cell;
}

//     item   
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
 CGFloat CWidth = imageHeight * SCREEN_RATE;
 CGFloat CHeight = imageHeight * SCREEN_RATE;
 return CGSizeMake(CWidth, CHeight);
}

#pragma mark - UICollectionViewDelegate    
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
 CollModel * model = self.modelArray[indexPath.row];
 NSLog(@"self.appModelArray----%@",model.title);
}


- (void)didReceiveMemoryWarning {
 [super didReceiveMemoryWarning];
 // Dispose of any resources that can be recreated.
}

@end
2、カスタムUICCollection View Flow Layout
LHHorizontalPageFlowlayout.h実現

#import <UIKit/UIKit.h>
@interface LHHorizontalPageFlowlayout : UICollectionViewFlowLayout
/**     */
@property (nonatomic, assign) CGFloat columnSpacing;
/**     */
@property (nonatomic, assign) CGFloat rowSpacing;
/** collectionView     */
@property (nonatomic, assign) UIEdgeInsets edgeInsets;

/**     */
@property (nonatomic, assign) NSInteger rowCount;
/**        item */
@property (nonatomic, assign) NSInteger itemCountPerRow;

//    
@property (nonatomic, assign) CGFloat itemWidth; //     ,         
//    
@property (nonatomic, assign) CGFloat itemHight;//     ,         

/**   item      */
@property (nonatomic, strong) NSMutableArray *attributesArrayM;

/**        collectionView     */
- (void)setColumnSpacing:(CGFloat)columnSpacing rowSpacing:(CGFloat)rowSpacing edgeInsets:(UIEdgeInsets)edgeInsets;
/**            item   */
- (void)setRowCount:(NSInteger)rowCount itemCountPerRow:(NSInteger)itemCountPerRow;

#pragma mark -     
/**            item   */
+ (instancetype)horizontalPageFlowlayoutWithRowCount:(NSInteger)rowCount itemCountPerRow:(NSInteger)itemCountPerRow;
/**            item   */
- (instancetype)initWithRowCount:(NSInteger)rowCount itemCountPerRow:(NSInteger)itemCountPerRow;

@end
LHHorizontalPageFlowlayout.m実現

#import "LHHorizontalPageFlowlayout.h"

@implementation LHHorizontalPageFlowlayout

#pragma mark - Public
- (void)setColumnSpacing:(CGFloat)columnSpacing rowSpacing:(CGFloat)rowSpacing edgeInsets:(UIEdgeInsets)edgeInsets
{
 self.columnSpacing = columnSpacing;
 self.rowSpacing = rowSpacing;
 self.edgeInsets = edgeInsets;
}

- (void)setRowCount:(NSInteger)rowCount itemCountPerRow:(NSInteger)itemCountPerRow
{
 self.rowCount = rowCount;
 self.itemCountPerRow = itemCountPerRow;
}

#pragma mark -     
+ (instancetype)horizontalPageFlowlayoutWithRowCount:(NSInteger)rowCount itemCountPerRow:(NSInteger)itemCountPerRow
{
 return [[self alloc] initWithRowCount:rowCount itemCountPerRow:itemCountPerRow];
}

- (instancetype)initWithRowCount:(NSInteger)rowCount itemCountPerRow:(NSInteger)itemCountPerRow
{
 self = [super init];
 if (self) {
  self.rowCount = rowCount;
  self.itemCountPerRow = itemCountPerRow;
 }
 return self;
}


#pragma mark -       
- (instancetype)init
{
 self = [super init];
 if (self) {
  [self setColumnSpacing:0 rowSpacing:0 edgeInsets:UIEdgeInsetsZero];
 }
 return self;
}

/**            */
- (void)prepareLayout
{
 [super prepareLayout];
 if (self.attributesArrayM && self.attributesArrayM.count > 0) {
  [self.attributesArrayM removeAllObjects];
 }
 
 //  collectionView        item
 NSInteger itemTotalCount = [self.collectionView numberOfItemsInSection:0];
 
 //    item attributes,               
 for (int i = 0; i < itemTotalCount; i++) {
  NSIndexPath *indexpath = [NSIndexPath indexPathForItem:i inSection:0];
  UICollectionViewLayoutAttributes *attributes = [self layoutAttributesForItemAtIndexPath:indexpath];
  [self.attributesArrayM addObject:attributes];
 }
}

/**   collectionView      */
- (CGSize)collectionViewContentSize
{
 //    item   
 CGFloat itemWidth = (self.collectionView.frame.size.width - self.edgeInsets.left - self.itemCountPerRow * self.columnSpacing) / self.itemCountPerRow;
 //  collectionView        item
 NSInteger itemTotalCount = [self.collectionView numberOfItemsInSection:0];
 
 //         item  
 NSInteger itemCount = self.rowCount * self.itemCountPerRow;
 //   (           item  )
 NSInteger remainder = itemTotalCount % itemCount;
 //   (      )
 NSInteger pageNumber = itemTotalCount / itemCount;
 //      self.rowCount * self.itemCountPerRow
 if (itemTotalCount <= itemCount) {
  pageNumber = 1;
 }else {
  if (remainder == 0) {
   pageNumber = pageNumber;
  }else {
   //     0,   1
   pageNumber = pageNumber + 1;
  }
 }
 
 CGFloat width = 0;
 //       ( item      self.rowCount * self.itemCountPerRow    ,                )
 if (pageNumber > 1 && remainder != 0 && remainder < self.itemCountPerRow) {
  width = self.edgeInsets.left + (pageNumber - 1) * self.itemCountPerRow * (itemWidth + self.columnSpacing) + remainder * itemWidth + (remainder - 1)*self.columnSpacing + self.edgeInsets.right;
 }else {
  width = self.edgeInsets.left + pageNumber * self.itemCountPerRow * (itemWidth + self.columnSpacing) - self.columnSpacing + self.edgeInsets.right;
 }
 
 //            
 return CGSizeMake(width, 150);
}

/**     item   (   frame) */
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
 // item         collectionView      
 CGFloat itemWidth = (self.collectionView.frame.size.width) / self.itemCountPerRow;
 CGFloat itemHeight = (self.collectionView.frame.size.height) / self.rowCount;
 
 NSInteger item = indexPath.item;
 //   item    
 NSInteger pageNumber = item / (self.rowCount * self.itemCountPerRow);
 NSInteger x = item % self.itemCountPerRow + pageNumber * self.itemCountPerRow;
 NSInteger y = item / self.itemCountPerRow - pageNumber * self.rowCount;
 
 //    item   
 CGFloat itemX = itemWidth * x;
 CGFloat itemY = itemHeight * y;
 
 UICollectionViewLayoutAttributes *attributes = [super layoutAttributesForItemAtIndexPath:indexPath];
 //   item frame
 attributes.frame = CGRectMake(itemX, itemY, itemWidth, itemHeight);
 
 return attributes;
}

/**   collectionView             */
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
 return self.attributesArrayM;
}


#pragma mark - Lazy
- (NSMutableArray *)attributesArrayM
{
 if (!_attributesArrayM) {
  _attributesArrayM = [NSMutableArray array];
 }
 return _attributesArrayM;
}
@end
4、カスタムセルとモデル
モデル

#import <Foundation/Foundation.h>

@interface CollModel : NSObject
@property (nonatomic,strong)NSString *imgUrl;
@property (nonatomic,strong)NSString *title;
@property (nonatomic,strong)NSString *url;
@end
カスタムセル

#import "imageCell.h"
//     
#define SCREEN_RATE  ([UIScreen mainScreen].bounds.size.width/375.0)

@interface imageCell()
@property (nonatomic, strong) UIImageView *itemIcon;
@end

@implementation imageCell

@synthesize itemModel = _itemModel;

- (instancetype)initWithFrame:(CGRect)frame{
 if (self = [super initWithFrame:frame]) {
  self.contentView.backgroundColor = [UIColor clearColor];
  [self initView];
 }
 return self;
}

- (void)initView{
 _itemIcon = [[UIImageView alloc] init];
 [self.contentView addSubview:_itemIcon];
 _itemIcon.backgroundColor = [UIColor clearColor];
 CGFloat iconWidth = 80 * SCREEN_RATE;
 _itemIcon.frame = CGRectMake(0, 0, iconWidth, iconWidth);
 _itemIcon.center = self.contentView.center;
}

- (CollModel *)itemModel{
 return _itemModel;
}

- (void)setItemModel:(CollModel *)itemModel
{
 if (!itemModel) {
  return;
 }
 _itemModel = itemModel;
 
 [self setCellWithModel:_itemModel];
}

- (void)setCellWithModel:(CollModel *)itemModel{
 [[NSOperationQueue mainQueue] addOperationWithBlock:^{
  _itemIcon.image = [UIImage imageNamed:itemModel.url];
 }];
}
ダウンロード:ios uicollection view横スクロール
GitHubダウンロード
以上が本文の全部です。皆さんの勉強に役に立つように、私たちを応援してください。