2013-10-13 61 views
1

如何讓應用在命中25個細胞後停止從陣列創建細胞?就目前而言,數組「cellArray」包含超過25個元素,並且沒有代碼可以阻止程序生成單元格。爲UICollectionView創建最大細胞數

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

如果你想25是最高,你可以這樣做:

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