MacBoss123541
MacBoss123541

Reputation: 198

Create a maximum cell count for UICollectionView

How do I make the app stop creating cells from the array after it hits 25 cells? As it stands, the array "cellArray" contains more than 25 elements, and there is no code to stop the program from producing cells.

CollectionViewContoller.m:

    @implementation CollectionViewController

//Delegate Methods

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

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

-(UICollectionViewCell*) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    Cell * aCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"bingoCell1" forIndexPath:indexPath];
    aCell.cellContent.text = self.cellArray[indexPath.row];
    return aCell;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        // Do any additional setup after loading the view.

        self.cellArray =
      @[@"Type 1", @"Type 2", @"Type 3", @"Type 4", @"Type 5", @"Type 6", @"Type 7", @"Type 8", @"Type 9", @"Type 10", @"Type 11", @"Type 12", @"Free Space", @"Type 14", @"Type 15", @"Type 16", @"Type 17", @"Type 18", @"Type 19", @"Type 20", @"Type 21", @"Type 22", @"Type 23", @"Type 24", @"Type 25", @"Type 58", @"Type 234"];

        NSIndexSet *beforeThirteen = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, 12)];
        NSIndexSet *afterThirteen  = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(13, self.cellArray.count-13)];

        //Build an array with all objects except for the thirteenth one and shuffle it
        NSMutableArray *arrayWithoutThirteenthObject = [NSMutableArray array];
        [arrayWithoutThirteenthObject addObjectsFromArray:[self.cellArray objectsAtIndexes:beforeThirteen]];
        [arrayWithoutThirteenthObject addObjectsFromArray:[self.cellArray objectsAtIndexes:afterThirteen]];
        [arrayWithoutThirteenthObject shuffle];

        //Add the thirteenth object into the shuffled array
        [arrayWithoutThirteenthObject insertObject:self.cellArray[12] atIndex:12];

        //Assign the array now with the thirteenth object at the thirteenth index and shuffled
        self.cellArray = arrayWithoutThirteenthObject;
    }

Upvotes: 1

Views: 1435

Answers (1)

Joel
Joel

Reputation: 16124

If you wanted 25 to be the max, you would do this:

-(NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return MIN(25, self.cellArray.count);
}

Upvotes: 5

Related Questions