ボタンをクリックしたiOSでUICollectionViewのデータを変更するにはどうすればよいですか?
-
21-12-2019 - |
質問
私は変化しようとしています UICollectionViewCell
ボタンクリック時のデータ(iPad)?これを達成するにはどうすればよいでしょうか?違う送り方 array count
に numberOfItemsInSection
ボタンをクリックしますか?
私の中で 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]'
解決
IBAction を介して UICollectionView にデータを追加/削除する方法を単に尋ねているだけだと思います。にオブジェクトを追加するだけです UICollectionView's
データソースとリロード。何かを追加する例を次に示します。
-(IBAction)addObject:(id)sender {
[self.objectArray addObject:@"new object"];
[self.myCollectionView reloadData];
}
他のヒント
さて、BOOL で 2 つの配列を保持し、タップに基づいて UicollectionView を再ロードし、最初に 2 つの配列を保持します
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];
}
これが機能することを願っています。私が間違いを犯した場合は、修正してください。
所属していません StackOverflow