使用UICollectionView创建按钮网格?

4
我希望创建一个带有按钮的网格。我看到的大多数示例应用程序都解释了如何创建图像网格,但没有一个解释了按钮的方法。
如何在UICollectionView的单元格中设置按钮?
以下是我的代码:

FirstViewController.h

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

FirstViewController.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.
}

CustomCell.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
3个回答

1
你正在出列的单元格不是CustomCell,因为你还没有告诉UICollectionViewCustomCell用作可重用单元格。
viewDidLoad:中添加此行:

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


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注册自定义单元格。


-1

这是针对UITableView单元格而非UICollectionView单元格的。 - Suragch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接