Ios 以编程方式在UICollectionView单元格的每个uiimage上添加UIButtons

Ios 以编程方式在UICollectionView单元格的每个uiimage上添加UIButtons,ios,objective-c,uiimageview,uicollectionviewcell,Ios,Objective C,Uiimageview,Uicollectionviewcell,我有一个UIViewController,其中包含一个通过编程方式创建的UICollectionView图像库。我想在UICollectionView单元格的每个uiimage上添加一个按钮: .h文件中的代码是: #import <UIKit/UIKit.h> @interface CMFViewController : UIViewController <UICollectionViewDataSource, UICollectionViewDelegate, UICol

我有一个UIViewController,其中包含一个通过编程方式创建的UICollectionView图像库。我想在UICollectionView单元格的每个uiimage上添加一个按钮: .h文件中的代码是:

#import <UIKit/UIKit.h>

@interface CMFViewController : UIViewController <UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>

@end
#import "CMFViewController.h"
#import "CMFGalleryCell.h"

@interface CMFViewController ()
@property (nonatomic, weak) IBOutlet UICollectionView *collectionView;
@property (nonatomic, strong) NSArray *dataArray;
@property (nonatomic) int currentIndex;

@end

@implementation CMFViewController

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

}

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


#pragma mark -
#pragma mark UICollectionView methods

-(void)setupCollectionView {
    [self.collectionView registerClass:[CMFGalleryCell class] forCellWithReuseIdentifier:@"cellIdentifier"];

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    [flowLayout setMinimumInteritemSpacing:0.0f];
    [flowLayout setMinimumLineSpacing:0.0f];
    [self.collectionView setPagingEnabled:YES];
    [self.collectionView setCollectionViewLayout:flowLayout];
   /*
    UICollectionViewLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    _collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];

    [_collectionView setDataSource:self];
    [_collectionView setDelegate:self];

    [_collectionView registerClass:[CMFGalleryCell class] forCellWithReuseIdentifier:@"Cell"];

    [self.view addSubview:_collectionView];*/
}


-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

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

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

    CMFGalleryCell *cell = (CMFGalleryCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];

    NSString *imageName = [self.dataArray objectAtIndex:indexPath.row];
    [cell setImageName:imageName];
   // [[cell myButton] addTarget:self action:@selector(myClickEvent:event) forControlEvents:UIControlEventTouchUpInside];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(80.0, 210.0, 100.0, 20.0);
    [button addTarget:self action:@selector(show) forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:@"ShowView" forState:UIControlStateNormal];





  //  NSMutableArray *buttonArray = [NSMutableArray arrayWithCapacity:100];

  //  for (int i = 0; i < 4; i++) {
       // NSUInteger index = arc4random() % 4;


        // newButton.frame = CGRectMake( 5,  5, 10, 10);    // Whatever position and size you need...

       // UIImage *buttonImage = [UIImage imageNamed:[self.dataArray objectAtIndex:indexPath.row]];
        //[newButton setBackgroundImage:buttonImage forState:UIControlStateNormal];

     //   [buttonArray addObject:newButton];
  //  }
   // newButton = buttonArray;   // Where myButtons is a NSArray property of your class, to store references to the buttons.

   // [newButton addTarget:self action:@selector(loadImages:) forControlEvents:UIControlEventTouchUpInside];
    //[newButton addTarget:self action:@selector(updateCell) forControlEvents:UIControlEventTouchUpInside];

    [cell updateCell];

    return cell;

}
/*
- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self)
    {

        // Create button

        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, 100, 100); // position in the parent view and set the size of the button
        [button setTitle:@"Title" forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:@"animage.png"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];

        // add to contentView
        //[self.contentView addSubview:button];
    }
    return self;
}*/
/*
-(void)updateCell
{

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 100, 100); // position in the parent view and set the size of the button
    [button setTitle:@"Title" forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"animage.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];

    [self collectionView];

}*/
// INSERT DELETE BUTTON ACTION SNIPPET HERE

#pragma mark - delete for button


-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return self.collectionView.frame.size;
}


#pragma mark -
#pragma mark Data methods
-(void)loadImages {

    NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Assets"];
    self.dataArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:sourcePath error:NULL];

}

#pragma mark -
#pragma mark Rotation handling methods

-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:
(NSTimeInterval)duration {

    // Fade the collectionView out
    [self.collectionView setAlpha:0.0f];

    // Suppress the layout errors by invalidating the layout
    [self.collectionView.collectionViewLayout invalidateLayout];

    // Calculate the index of the item that the collectionView is currently displaying
    CGPoint currentOffset = [self.collectionView contentOffset];    
    self.currentIndex = currentOffset.x / self.collectionView.frame.size.width;
}

-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {

    // Force realignment of cell being displayed
    CGSize currentSize = self.collectionView.bounds.size;
    float offset = self.currentIndex * currentSize.width;
    [self.collectionView setContentOffset:CGPointMake(offset, 0)];

    // Fade the collectionView back in
    [UIView animateWithDuration:0.125f animations:^{
        [self.collectionView setAlpha:1.0f];
    }];

}

@end
#导入
@接口CMFViewController:UIViewController
@结束
.m文件中的代码是:

#import <UIKit/UIKit.h>

@interface CMFViewController : UIViewController <UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>

@end
#import "CMFViewController.h"
#import "CMFGalleryCell.h"

@interface CMFViewController ()
@property (nonatomic, weak) IBOutlet UICollectionView *collectionView;
@property (nonatomic, strong) NSArray *dataArray;
@property (nonatomic) int currentIndex;

@end

@implementation CMFViewController

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

}

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


#pragma mark -
#pragma mark UICollectionView methods

-(void)setupCollectionView {
    [self.collectionView registerClass:[CMFGalleryCell class] forCellWithReuseIdentifier:@"cellIdentifier"];

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    [flowLayout setMinimumInteritemSpacing:0.0f];
    [flowLayout setMinimumLineSpacing:0.0f];
    [self.collectionView setPagingEnabled:YES];
    [self.collectionView setCollectionViewLayout:flowLayout];
   /*
    UICollectionViewLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    _collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];

    [_collectionView setDataSource:self];
    [_collectionView setDelegate:self];

    [_collectionView registerClass:[CMFGalleryCell class] forCellWithReuseIdentifier:@"Cell"];

    [self.view addSubview:_collectionView];*/
}


-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

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

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

    CMFGalleryCell *cell = (CMFGalleryCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];

    NSString *imageName = [self.dataArray objectAtIndex:indexPath.row];
    [cell setImageName:imageName];
   // [[cell myButton] addTarget:self action:@selector(myClickEvent:event) forControlEvents:UIControlEventTouchUpInside];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(80.0, 210.0, 100.0, 20.0);
    [button addTarget:self action:@selector(show) forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:@"ShowView" forState:UIControlStateNormal];





  //  NSMutableArray *buttonArray = [NSMutableArray arrayWithCapacity:100];

  //  for (int i = 0; i < 4; i++) {
       // NSUInteger index = arc4random() % 4;


        // newButton.frame = CGRectMake( 5,  5, 10, 10);    // Whatever position and size you need...

       // UIImage *buttonImage = [UIImage imageNamed:[self.dataArray objectAtIndex:indexPath.row]];
        //[newButton setBackgroundImage:buttonImage forState:UIControlStateNormal];

     //   [buttonArray addObject:newButton];
  //  }
   // newButton = buttonArray;   // Where myButtons is a NSArray property of your class, to store references to the buttons.

   // [newButton addTarget:self action:@selector(loadImages:) forControlEvents:UIControlEventTouchUpInside];
    //[newButton addTarget:self action:@selector(updateCell) forControlEvents:UIControlEventTouchUpInside];

    [cell updateCell];

    return cell;

}
/*
- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self)
    {

        // Create button

        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, 100, 100); // position in the parent view and set the size of the button
        [button setTitle:@"Title" forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:@"animage.png"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];

        // add to contentView
        //[self.contentView addSubview:button];
    }
    return self;
}*/
/*
-(void)updateCell
{

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 100, 100); // position in the parent view and set the size of the button
    [button setTitle:@"Title" forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"animage.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];

    [self collectionView];

}*/
// INSERT DELETE BUTTON ACTION SNIPPET HERE

#pragma mark - delete for button


-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return self.collectionView.frame.size;
}


#pragma mark -
#pragma mark Data methods
-(void)loadImages {

    NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Assets"];
    self.dataArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:sourcePath error:NULL];

}

#pragma mark -
#pragma mark Rotation handling methods

-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:
(NSTimeInterval)duration {

    // Fade the collectionView out
    [self.collectionView setAlpha:0.0f];

    // Suppress the layout errors by invalidating the layout
    [self.collectionView.collectionViewLayout invalidateLayout];

    // Calculate the index of the item that the collectionView is currently displaying
    CGPoint currentOffset = [self.collectionView contentOffset];    
    self.currentIndex = currentOffset.x / self.collectionView.frame.size.width;
}

-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {

    // Force realignment of cell being displayed
    CGSize currentSize = self.collectionView.bounds.size;
    float offset = self.currentIndex * currentSize.width;
    [self.collectionView setContentOffset:CGPointMake(offset, 0)];

    // Fade the collectionView back in
    [UIView animateWithDuration:0.125f animations:^{
        [self.collectionView setAlpha:1.0f];
    }];

}

@end
#导入“CMFViewController.h”
#导入“CMFGalleryCell.h”
@接口CMFViewController()
@属性(非原子,弱)IBUICollectionView*collectionView;
@属性(非原子,强)NSArray*数据数组;
@属性(非原子)int currentIndex;
@结束
@CMFViewController的实现
-(无效)viewDidLoad
{
[超级视图下载];
//加载视图后,通常从nib执行任何其他设置。
[自动加载图像];
[自设置集合视图];
}
-(无效)未收到记忆警告
{
[超级记忆警告];
//处置所有可以重新创建的资源。
}
#布拉格标记-
#pragma标记UICollectionView方法
-(无效)setupCollectionView{
[self.collectionView注册表类:[CMFGalleryCell类]forCellWithReuseIdentifier:@“cellIdentifier”];
UICollectionViewFlowLayout*flowLayout=[[UICollectionViewFlowLayout alloc]init];
[flowLayout设置滚动方向:UICollectionViewScrollDirection水平];
[flowLayout SetMinimuminemSpacing:0.0f];
[流程布局设置最小线间距:0.0f];
[self.collectionView SetPaginEnabled:是];
[self.collectionView setCollectionViewLayout:flowLayout];
/*
UICollectionViewLayout*布局=[[UICollectionViewFlowLayout alloc]init];
_collectionView=[[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
[\u collectionView setDataSource:self];
[[u collectionView setDelegate:self];
[\u collectionView注册表类:[CMFGalleryCell类]forCellWithReuseIdentifier:@“Cell”];
[self.view addSubview:_collectionView]*/
}
-(NSInteger)collectionView中的节数:(UICollectionView*)collectionView{
返回1;
}
-(NSInteger)collectionView:(UICollectionView*)collectionView项目编号截面:(NSInteger)截面{
返回[self.dataArray count];
}
-(UICollectionViewCell*)collectionView:(UICollectionView*)collectionView cellForItemAtIndexPath:(NSIndexPath*)indexPath{
CMFGalleryCell*单元格=(CMFGalleryCell*)[collectionView dequeueReusableCellWithReuseIdentifier:@“cellIdentifier”forIndexPath:indexPath];
NSString*imageName=[self.dataArray objectAtIndex:indexath.row];
[单元格设置imageName:imageName];
//[[cell myButton]添加目标:自我操作:@selector(myClickEvent:event)for ControlEvents:UIControlEventTouchUpInside];
UIButton*button=[UIButton button类型:UIButtonyPeroundRect];
button.frame=CGRectMake(80.0、210.0、100.0、20.0);
[按钮添加目标:自我操作:@selector(show)for ControlEvents:UIControlEventTouchUpInside];
[按钮设置标题:@“ShowView”状态:UIControlStateNormal];
//NSMutableArray*buttonArray=[NSMutableArray阵列容量:100];
//对于(int i=0;i<4;i++){
//NSU整数索引=arc4random()%4;
//newButton.frame=CGRectMake(5,5,10,10);//您需要的任何位置和大小。。。
//UIImage*buttonImage=[UIImage ImageName:[self.dataArray objectAtIndex:indexath.row]];
//[newButton setBackgroundImage:buttonImage for状态:UIControlStateNormal];
//[buttonArray addObject:newButton];
//  }
//newButton=buttonArray;//其中myButtons是类的NSArray属性,用于存储对按钮的引用。
//[newButton addTarget:self action:@selector(loadImages:)forControlEvents:UIControlEventTouchUpInside];
//[newButton addTarget:self action:@selector(updateCell)for ControlEvents:UIControlEventTouchUpInside];
[细胞更新细胞];
返回单元;
}
/*
-(id)initWithCoder:(NSCoder*)aDecoder
{
self=[super initWithCoder:aDecoder];
如果(自我)
{
//创建按钮
UIButton*button=[UIButton button类型:UIButtonTypeCustom];
button.frame=CGRectMake(0,0,100,100);//在父视图中定位并设置按钮的大小
[按钮设置标题:@“标题”用于状态:uicontrol状态正常];
[按钮设置图像:[UIImage ImageName:@“animage.png”]用于状态:UIControlStateNormal];
[按钮添加目标:自我操作:@选择器(按钮:)for ControlEvents:UIControlEventTouchUpInside];
//添加到contentView
//[self.contentView addSubview:按钮];
}
回归自我;
}*/
/*
-(void)updateCell
{
UIButton*button=[UIButton button类型:UIButtonTypeCustom];
button.frame=CGRectMake(0,0,100,100);//在父视图中定位并设置按钮的大小
[按钮设置标题:@“标题”用于状态:uicontrol状态正常];
[按钮设置图像:[UIImage ImageName:@“animage.png”]用于状态:UIControlStateNormal];
[按钮添加目标:自我操作:@选择器(按钮:)for ControlEvents:UIControlEventTouchUpInside];
[自我收集视图];
}*/
//在此处插入删除按钮操作片段
#pragma标记-删除按钮
-(CGSize)collectionView:(UICollectionView*)collectionView布局:(UICollectionViewLayout*)collectionViewLayout大小FormiteIndeXPath:(NSIndexPath*)indexPath{
返回self.collectionView.frame.size;
}
#布拉格标记-
#pragma标记数据方法
-(void)加载图像{
NSString*sourcePath=[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:@“资产”];
self.dataArray=[[NSFileManager defaultManager]contentsOfDirectoryAtPath:sourcePath错误:NULL];
}
#布拉格标记-
#pragma标记旋转处理方法
-(无效)将旋转接口方向:(UIInterfaceOrientation)到接口方向持续时间:
(NSTimeInterval)持续时间{
//淡出collectionView
[self.collectionView setAlpha:0.0f];
//通过使布局无效来抑制布局错误
[self.collectionView.collectionViewLayout invalidateLayout];