如何在按钮单击ios上更改UICollectionView的数据?

时间:2014-02-25 13:13:48

标签: ios uicollectionview

我正在尝试更改按钮点击(在iPad中)的UICollectionViewCell数据? 怎么做到这一点? 如何在按钮上发送不同的array countnumberOfItemsInSection点击?

在我的viewDidLoad

self.collectionViewImages=[[NSMutableArray alloc]initWithObjects:@"1.jpg",@"2.jpg",@"3.jpg",nil] ;

然后在CollectionViewMethods

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

    return [_collectionViewImages count];

}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
             cellForItemAtIndexPath:(NSIndexPath *)indexPath
{

   UICollectionViewCell *myCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell"
                                forIndexPath:indexPath];


   NSString *collectionViewImageName=[self.collectionViewImages objectAtIndex:indexPath.row];
   UIImageView * collectionImage = (UIImageView*)[myCell viewWithTag:11];

  collectionImage.image =[UIImage imageNamed:collectionViewImageName];

 return myCell;
}

然后在ButtonClick-- (由于有4-5个按钮,我正在收集NSInteger中每个按钮的标记,并在numberOfItemsInSection中使用该属性,

-(void)btnTapped:(id)sender{
int tag= [(UIButton *)sender tag];
NSLog(@"Button Pressed%d",tag);
_buttonIndex=tag;
//_buttonIndex is NSInteger property
//If i add object in NSMutableArray and call reloadData my UI hangs here only.
//If  I empty my NSMutableArray and add new objects in it and then call reloadData, I am getting NSRangeException. 
}

现在我在numberOfItemsInSection中使用此属性作为...

if (_buttonIndex==1){

     [collectionImage setImage:[UIImage imageNamed:[_array1 objectAtIndex:indexPath.row]]];
     //My _array1 has 4 objects and my collectionViewImages array has 7 objects.

    }

我收到错误消息

*** Terminating app due to uncaught exception 'NSRangeException', 
reason: '*** -[__NSArrayM objectAtIndex:]: index 4 beyond bounds [0 .. 3]'

2 个答案:

答案 0 :(得分:2)

你保持两个数组与BOOL并基于水龙头你重新加载UicollectionView首先保持两个数组

声明BOOL

BOOL isChangeData;

前:

 self.collectionViewImages=[[NSMutableArray alloc]initWithObjects:@"1.jpg",@"2.jpg",@"3.jpg",nil] ;

 self.collectionViewImages1=[[NSMutableArray alloc]initWithObjects:@"4.jpg",@"5.jpg",@"6.jpg",nil] ;

 isChangeData = TRUE;

首次将原始数据设置为数据源

-(NSInteger)collectionView:(UICollectionView *)collectionView
numberOfItemsInSection:(NSInteger)section
{
    if(isChangeData){

    isChangeData = false;

    return [_collectionViewImages1 count];
     }

else{

    isChangeData = TRUE;

    return [_collectionViewImages count];
}

}
按钮操作中的

将BOOL设为true并重新加载UICOllectionView

-(IBAction)changeData:(id)sender {

 [self.CollectionView reloadData];
}

如果我犯了任何错误,希望这是有效的,请纠正我。

答案 1 :(得分:0)

我相信你只是在询问如何通过IBAction从UICollectionView添加/删除数据。您只需将对象添加到UICollectionView's数据源并重新加载即可。以下是添加内容的示例:

-(IBAction)addObject:(id)sender {
  [self.objectArray addObject:@"new object"];
  [self.myCollectionView reloadData];
}