Vuko
Vuko

Reputation: 109

ios - horizontally scrolling collectionView with images

I am trying to show images on collectionView. I have trouble showing this images as I have created a reusable cell with imageView inside.Those images have to be equally spaced between as I want to show 3 icons on screen at once. I am using 13 icons and it has to be scrollable horizontally through screen.

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;
 }

Upvotes: 0

Views: 3117

Answers (2)

user3182143
user3182143

Reputation: 9589

Now OP wants horizontal scrollable direction of Collection view.So Again I created small sample project for this.I put 13 images in horizontal scroll direction.It scrolls successfully on horizontal direction of collection view.

Why I post the horizontal scrollable collectionView here is everyone can understand the answer and get the solution easily.I added extra image I mean exactly 13 images(op wants 13 images into collection view). This answer definitely helps you.

HorizontalScrollableCollectionView

Here I set the scrollDirection as Horizontal in CustomImageFlowLayout.m file

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

Then CustomCell of UICollectionViewCell

CustomCell.xib

enter image description here

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

Now Storyboard design starts

enter image description here

My collection view name is here collectionviewVerticalHorizontalFlowLayout

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

Final out put screen shots

First it shows

enter image description here

Then If I scroll horizontally in the collection view it shows

enter image description here

Upvotes: 2

user3182143
user3182143

Reputation: 9589

I will give you what you ask.

I wanted to same thing in one application.I successfully implemented this.Just now I tried the sample project for your question.I got what you ask exactly.I show you the code and everything below.

First CustomImageFlowLayout of NSObject Class

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

After that I created Custom Cell for Images

See my Design first

enter image description here

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

Then I use above class in my ViewController

Below is my Storyboard Design

enter image description here

Here my CollectionView name is 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);
}

Finally the output screen

enter image description here

Upvotes: 2

Related Questions