ios - 使用图像

时间:2017-03-22 16:02:27

标签: ios objective-c image uiscrollview uicollectionviewcell

我正在尝试在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;
 }

2 个答案:

答案 0 :(得分: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

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

先看我的设计

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

然后我在 ViewController

中使用上面的类

以下是我的故事板设计

enter image description here

这里我的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);
}

最后是输出屏幕

enter image description here

答案 1 :(得分:1)

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

为什么我在这里发布水平可滚动集合视图是每个人都可以理解答案并轻松获得解决方案。我添加了额外的图像我的意思是13个图像(操作需要13个图像进入集合视图)。这个答案绝对可以帮到你。

<强> 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

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

现在故事板设计启动

enter image description here

我的集合视图名称在这里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

最终输出屏幕截图

首先显示

enter image description here

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

enter image description here