以编程方式将UIButtons添加到UICollectionView单元的uiimage

时间:2014-11-12 05:02:03

标签: ios objective-c iphone uibutton uiimage

我有一个UIViewController,它以编程方式在其中创建了一个UICollectionView图像库。我想在UICollectionView单元的每个uiimage上添加一个按钮:CMFViewController.h.m文件中用于向imageview添加按钮的代码是:

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

}

我必须通过以下链接获取代码的帮助 adding-a-uibutton-to-a-uicollectionview

UIButton in cell in collection view not receiving touch up inside event 请提出我的建议并帮助我解决这个问题。

从此链接中,您可以在source code下载Creating a Paged Photo Gallery With a UICollectionView:他们我想在屏幕的每个图像的中间行放置下一个和上一个按钮

2 个答案:

答案 0 :(得分:1)

为了实现下一个和上一个按钮,不要在每个图像上添加它,更好的是你将它添加到集合视图上,chinttu-maddy-ramani在他的回答中说的是正确的,但是他在xib文件中做,但是以编程方式你可以像下面这样做,

只需添加此代码

编辑要求更新按钮

CMFViewController.h文件中的

创建两个按钮属性 替换为以下代码

 #import <UIKit/UIKit.h>

 @interface CMFViewController : UIViewController <UICollectionViewDataSource,   UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
 @property (nonatomic, strong) UIButton *nextButton;
 @property (nonatomic, strong) UIButton *prevButton;
 @end
<{1>}文件中的

CMFViewController.m

答案 1 :(得分:0)

您可以在单元格中添加按钮以直接拖动&amp; CMFGalleryCell.xib中的下拉按钮,请检查附加屏幕截图。并添加按钮约束以水平居中,并与您的单元格垂直居中。

enter image description here

仅供建议如果您想要下一个上一个功能,那么您还可以在CMFViewController.xib中的主xib中添加按钮,如下图所示。

enter image description here