ios - 使用图像水平滚动collectionView

Posted

技术标签:

【中文标题】ios - 使用图像水平滚动collectionView【英文标题】:ios - horizontally scrolling collectionView with images 【发布时间】:2017-03-22 16:02:27 【问题描述】:

我正在尝试在 collectionView 上显示图像。我在显示这些图像时遇到了麻烦,因为我创建了一个内部带有 imageView 的可重复使用的单元格。这些图像之间必须等距,因为我想一次在屏幕上显示 3 个图标。我使用了 13 个图标,并且它必须可以在屏幕上水平滚动。

我无法在单元格中显示图像,并且我不知道如何使用一个可重复使用的单元格来设置图像单元格之间的间距

CustomCollectionViewCell.h

@interface CustomCollectionViewCell : UICollectionViewCell
@property (nonatomic, retain) UIImageView *imageView;

@end

CustomCollectionViewCell.m

   @implementation CustomCollectionViewCell

    - (UIImageView *) imageView 

   if (!_imageView) 
      _imageView = [[UIImageView alloc]      initWithFrame:self.contentView.bounds];
    [self.contentView addSubview:_imageView];


return _imageView;
   

   - (void)prepareForReuse 

    [super prepareForReuse];

[self.imageView removeFromSuperview];
self.imageView = nil;

@end

LandingViewController.m

   - (UICollectionViewCell *)collectionView:(UICollectionView *)cv     cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath 

   CustomCollectionViewCell *cell = [cv    dequeueReusableCellWithReuseIdentifier:@"CustomCell" forIndexPath:indexPath];

return cell;
 

【问题讨论】:

其实我之前已经实现了。感谢您抽出宝贵时间回答我的问题。 【参考方案1】:

现在 OP 想要集合视图的水平滚动方向。所以我再次为此创建了一个小示例项目。我在水平滚动方向放置了 13 个图像。它在集合视图的水平方向上成功滚动。

为什么我在这里发布水平滚动collectionView是每个人都可以理解答案并轻松获得解决方案。我添加了额外的图像,我的意思是正好13张图片(op希望13张图片进入collection view)。这个答案肯定对你有帮助。

Horizo​​ntalScrollableCollectionView

这里我在CustomImageFlowLayout.m文件中将scrollDirection设置为Horizo​​ntal

CustomImageFlowLayout.h

#import <UIKit/UIKit.h>
@interface CustomImageFlowLayout : UICollectionViewFlowLayout
@end

CustomImageFlowLayout.m

#import "CustomImageFlowLayout.h"

@implementation CustomImageFlowLayout

- (instancetype)init

    self = [super init];
    if (self)
    
        self.minimumLineSpacing = 1.0f;
        self.minimumInteritemSpacing = 1.0f;
        self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    return self;


- (CGSize)itemSize

    NSInteger numberOfColumns;
    if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
       numberOfColumns = 3;
    else
        if([UIApplication sharedApplication].statusBarOrientation==UIInterfaceOrientationPortrait)
            numberOfColumns = 4;
        else if([UIApplication sharedApplication].statusBarOrientation == UIDeviceOrientationLandscapeRight || [UIApplication sharedApplication].statusBarOrientation == UIDeviceOrientationLandscapeLeft)
            numberOfColumns = 4;
    
    NSLog(@"The collection view frame is - %@",NSStringFromCGRect(self.collectionView.frame));
    CGFloat itemWidth = (CGRectGetWidth(self.collectionView.frame) - (numberOfColumns - 1)) / numberOfColumns;
    NSLog(@"The item width is - %f",itemWidth);
    return CGSizeMake(itemWidth, itemWidth);


@end

然后是 UICollectionViewCell 的 CustomCell

CustomCell.xib

CustomCell.h

#import <UIKit/UIKit.h>
@interface CustomCell : UICollectionViewCell
@property (strong, nonatomic) IBOutlet UIImageView *img;
@property (strong, nonatomic) IBOutlet UILabel *lblCollection;
@end

CustomCell.m

#import "CustomCell.h"
@implementation CustomCell
- (void)awakeFromNib 
    [super awakeFromNib];
    // Initialization code

@end

现在故事板设计开始

我的集合视图名称在这里是collectionviewVerticalHorizo​​ntalFlowLayout

ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UICollectionViewDelegate,UICollectionViewDataSource>

@property (strong, nonatomic) IBOutlet UICollectionView *collectionviewVerticalHorizontalFlowLayout;

@end

ViewController.m

#import "ViewController.h"
#import "CustomCell.h"
#import "CustomImageFlowLayout.h"


@interface ViewController ()
    NSMutableArray *arrayImages;
    NSMutableArray *arrayTitles;
    CustomCell *cell;


@end

@implementation ViewController

@synthesize collectionviewVerticalHorizontalFlowLayout;

- (void)viewDidLoad 
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    collectionviewVerticalHorizontalFlowLayout.collectionViewLayout = [[CustomImageFlowLayout alloc] init];
    collectionviewVerticalHorizontalFlowLayout.backgroundColor = [UIColor clearColor];

    arrayImages = [[NSMutableArray alloc]initWithObjects:@"iPhone.png", @"android.png", @"windows.png", @"blackberry.png", @"lenovovibek5note.png", @"redmi.png", @"moto.png", @"sony.png", @"samsung.png", @"oneplus.png",@"redminote4.png",@"oppo.png",@"vivo.png",nil];
    arrayTitles = [[NSMutableArray alloc]initWithObjects:@"iPhone", @"Android", @"Windows", @"Blackberry", @"LenovaVikeK5Note", @"Redmi", @"MotoG", @"Sony", @"Samsung", @"OnePlus", @"RedMiNote4",@"Oppo",@"Vivo",nil];

    UINib *cellNib = [UINib nibWithNibName:@"CustomCell" bundle:nil];
    [collectionviewVerticalHorizontalFlowLayout registerNib:cellNib forCellWithReuseIdentifier:@"cell"];




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


//UICollectionView Data Source Methods
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView

    return  1;


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section

    return arrayImages.count;


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

    static NSString *cellIdentifier = @"cell";
    cell = (CustomCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    if(cell==nil)
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
        cell = nib[0];
    
    cell.img.image = [UIImage imageNamed:(NSString*)[arrayImages objectAtIndex:indexPath.row]];
    NSLog(@"The collection view label text is - %@",[NSString stringWithFormat:@"%@",arrayTitles[indexPath.row]]);
    cell.lblCollection.text = arrayTitles[indexPath.row];
    cell.lblCollection.textColor = [UIColor blackColor];
    return cell;


//UICollectionView Delegate Method
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

    NSLog(@"the clicked indexPath.row is - %ld",(long)indexPath.row);



@end

最后的截图

首先显示

然后如果我在集合视图中水平滚动它会显示

【讨论】:

【参考方案2】:

我会满足你的要求。

我想在一个应用程序中做同样的事情。我成功地实现了这个。刚才我尝试了你的问题的示例项目。我得到了你确切的要求。我向你展示了下面的代码和所有内容。

NSObject 类的第一个CustomImageFlowLayout

CustomImageFlowLayout.h

#import <UIKit/UIKit.h>
@interface CustomImageFlowLayout : UICollectionViewFlowLayout
@end

CustomImageFlowLayout.m

#import "CustomImageFlowLayout.h"

@implementation CustomImageFlowLayout

- (instancetype)init

    self = [super init];
    if (self)
    
        self.minimumLineSpacing = 1.0f;
        self.minimumInteritemSpacing = 1.0f;
        self.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    return self;


- (CGSize)itemSize

    NSInteger numberOfColumns;
    if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
       numberOfColumns = 3;
    else
        if([UIApplication sharedApplication].statusBarOrientation==UIInterfaceOrientationPortrait)
            numberOfColumns = 4;
        else if([UIApplication sharedApplication].statusBarOrientation == UIDeviceOrientationLandscapeRight || [UIApplication sharedApplication].statusBarOrientation == UIDeviceOrientationLandscapeLeft)
            numberOfColumns = 4;
    
    NSLog(@"The collection view frame is - %@",NSStringFromCGRect(self.collectionView.frame));
    CGFloat itemWidth = (CGRectGetWidth(self.collectionView.frame) - (numberOfColumns - 1)) / numberOfColumns;
    NSLog(@"The item width is - %f",itemWidth);
    return CGSizeMake(itemWidth, itemWidth);


@end

之后我为图像创建了自定义单元格

先看看我的设计

CustomCell.h

#import <UIKit/UIKit.h>
@interface CustomCell : UICollectionViewCell
@property (strong, nonatomic) IBOutlet UIImageView *img;
@property (strong, nonatomic) IBOutlet UILabel *lblCollection;
@end

CustomCell.m

#import "CustomCell.h"
@implementation CustomCell
@end

然后我在 ViewController

中使用上述类

下面是我的故事板设计

这里我的 CollectionView 名称是 collectionViewVertical

ViewController.h

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
@property (strong, nonatomic) IBOutlet UICollectionView *collectionViewVertical;
@end

ViewController.m

#import "ViewController.h"
#import "CustomCell.h"
#import "CustomImageFlowLayout.h"
@interface ViewController ()

    NSMutableArray *arrayImages;
    NSMutableArray *arrayTitles;
    CustomCell *cell;

@end

@implementation ViewController

@synthesize collectionViewVertical;

- (void)viewDidLoad

    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    collectionViewVertical.collectionViewLayout = [[CustomImageFlowLayout alloc] init];
    collectionViewVertical.backgroundColor = [UIColor clearColor];

    arrayImages = [[NSMutableArray alloc]initWithObjects:@"iPhone", @"Android", @"Windows", @"Blackberry", @"Lenova", @"Redmi", @"MotoG", @"Sony", @"Samsung", @"OnePlus", nil];
    arrayTitles = [[NSMutableArray alloc]initWithObjects:@"iPhone.png", @"android.png", @"windows.png", @"blackberry.png", @"lenovo.png", @"redmi.png", @"moto.png", @"sony.png", @"samsung.png", @"oneplus.png", nil];

    UINib *cellNib = [UINib nibWithNibName:@"CustomCell" bundle:nil];
    [collectionViewVertical registerNib:cellNib forCellWithReuseIdentifier:@"cell"];


- (void)didReceiveMemoryWarning

    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.


//UICollectionView Data Source Methods
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView

    return  1;


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section

    return arrayImages.count;


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

    static NSString *cellIdentifier = @"cell";
    cell = (CustomCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    if(cell==nil)
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
        cell = nib[0];
    
    cell.img.image = [UIImage imageNamed:(NSString*)[arrayImages objectAtIndex:indexPath.row]];
    cell.lblCollection.text = arrayTitles[indexPath.row];

    return cell;


//UICollectionView Delegate Method
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

    NSLog(@"the clicked indexPath.row is - %ld",(long)indexPath.row);

终于输出画面了

【讨论】:

以上是关于ios - 使用图像水平滚动collectionView的主要内容,如果未能解决你的问题,请参考以下文章

无法使用 IOS 的 ScrollView 水平滚动

如何防止'GMSMapView'无限水平滚动?

ios水平滚动视图和自动布局问题

UIimage没有出现在iOS中的滚动视图上

如何使用不同大小和方向的图像创建水平滚动视图?

区分点击和滚动 - iOS