Reputation: 117
I have a very strange problem with UICollectionView
. whenever I try to reload my collection view via [mycollectopn reloaddata]
, item sequence becomes change.
For example I have 9 items in my collection view with mybutton1 at item 0 but whenever I reload the collection view, mybutton1 goes to 6th position and same behavior with all other items.
Does anybody had the same problem before? Any help will be appreciated. this is what I've done
-(NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView {
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return [BtnImgArray count];
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *myCell = [collectionView
dequeueReusableCellWithReuseIdentifier:@"collection"
forIndexPath:indexPath];
UIButton *btn = (UIButton *)[myCell viewWithTag:10];
btn.tag = indexPath.row;
[btn setImage:[UIImage imageNamed:[BtnImgArray objectAtIndex:indexPath.row]] forState:UIControlStateNormal];
[btn setImage:[UIImage imageNamed:[BtnImgArraySelected objectAtIndex:indexPath.row]] forState:UIControlStateSelected];
btn.titleLabel.textAlignment = NSTextAlignmentCenter;
if (indexPath.item==0 && ModeOfSpa == 0)
{
[btn setSelected:true];
[btn setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
}
else if(indexPath.row ==1 && ModeOfSpa == 1)
{
[btn setSelected:true];
[btn setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
}
else
{
btn.titleLabel.textColor = [UIColor whiteColor];
}
if (indexPath.item== 4) {
[btn setTitle:[NSString stringWithFormat:@"%@\n%@",@"All On", @"Mode"] forState:UIControlStateNormal];
}
else if (indexPath.item== 5) {
[btn setTitle:[NSString stringWithFormat:@"%@\n%@",@"Clean", @"Mode"] forState:UIControlStateNormal];
}
else{
NSString * str = [detailvwlblArray objectAtIndex:indexPath.row];
[btn setTitle:[str substringFromIndex:9] forState:UIControlStateNormal];
}
[btn addTarget:self action:@selector(BtnClicked:) forControlEvents:UIControlEventTouchUpInside];
return myCell;
}
and in viewWillAppear
, I used [myCollectionView ReloadData]
Upvotes: 0
Views: 996
Reputation: 119031
It's your logical error. Initially your buttons are tagged '10' and the first time a cell is used you get the button using that tag:
UIButton *btn = (UIButton *)[myCell viewWithTag:10];
But then you change the tag:
btn.tag = indexPath.row;
So the next time you try to get it you can't, and none of your updates work.
Quick and dirty solution: reset the tag when the cell is removed from display. Use tableView:didEndDisplayingCell:forRowAtIndexPath:
where you can get the button with the index path for the tag and reset it to 10
.
Correct solution: don't use tags, setup a proper relationship between the button, cell and controller so you know the index path that was tapped.
Upvotes: 1