4

我想用按钮创建一个网格。我看到的大多数示例应用程序都解释了如何创建图像网格,但没有一个解释按钮。

如何在UICollectionView单元格中设置按钮?

这是我的代码,

第一视图控制器.h

#import <UIKit/UIKit.h>
@interface FirstViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegate>
@property (weak, nonatomic) IBOutlet UICollectionView *myCollectView;
@end

第一视图控制器.m

#import "FirstViewController.h"
#import "CustomCell.h"

@interface FirstViewController ()
{
    NSArray *arrayOfBtns;
}
@end

@implementation FirstViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [[self myCollectView]setDelegate:self];
    [[self myCollectView]setDataSource:self];
    // Do any additional setup after loading the view, typically from a nib.
    arrayOfBtns=[[NSArray alloc]initWithObjects:@"Save",@"Goto", nil];
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [arrayOfBtns count];
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier=@"Cell";
    CustomCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    //[[cell btn]setText:[arrayOfBtns objectAtIndex:indexPath.item  ]];
    return cell;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

自定义单元格.h

    #import <UIKit/UIKit.h>

@interface CustomCell : UICollectionViewCell
@property (weak, nonatomic) IBOutlet UIButton *btn;

@end

CustomCell.m

 #import "CustomCell.h"

@implementation CustomCell

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}
- (IBAction)btn:(id)sender {
}
@end
4

3 回答 3

1

您要出列的单元格不是 a CustomCell,因为您没有告诉您将UICollectionViewCustomCell用作可重复使用的单元格。

viewDidLoad:中,添加以下行:

[[self myCollectionView] registerClass:[CustomCell class] forCellWithReuseIdentifier:@"Cell"];

于 2013-09-17T08:50:38.600 回答
0
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    CustomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    //[cell.btn setText:[arrayOfBtns objectAtIndex:indexPath.item]];
    return cell;
}

单元格为零。您应该为 CellIdentifier 注册自定义单元格。

于 2013-09-17T09:02:34.750 回答
-1

您可以在此处找到如何创建自定义单元格:http ://www.goapps.pl/blog/perfecting-uitableview-step-one-custom-cells/

于 2013-09-17T08:52:34.130 回答