Button grid using UICollectionView?

I want to create a grid with buttons. Most of the sample applications I've seen explain how to create an image grid, but none of them explain for buttons.

How to set a button in a cell UICollectionView?

Here is my code

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
+4
source share
3 answers

The cell you are executing is not CustomCell, because you were not told to UICollectionViewuse CustomCellreusable cells.

In viewDidLoad:add this line:

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

+1
-(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.

0
-one
source

Source: https://habr.com/ru/post/1502554/


All Articles