1

如何让应用程序在达到 25 个单元格后停止从数组创建单元格?就目前而言,数组“cellArray”包含超过 25 个元素,并且没有代码可以阻止程序生成单元格。

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;
    }
4

1 回答 1

5

如果您希望 25 成为最大值,您可以这样做:

-(NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return MIN(25, self.cellArray.count);
}
于 2013-10-13T06:24:30.973 回答