Reputation: 411
Is there something wrong with UICollectionView
s? I am looking at several posts about them not reusing cells. My project firstly only fills in the first 15 then when you scroll back they are all to pot? Help please code below:
#import "CollectionView.h"
@interface CollectionView ()
@end
@implementation CollectionView
@synthesize list;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
list = [[NSMutableArray alloc]init];
[self fillArray];
}
-(void)fillArray
{
for (int i=1; i<31; i++) {
[list addObject:[NSString stringWithFormat:@"%ithumb",i]];
}
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:
(NSInteger)section {
return list.count;
}
- (void)createScreen:(UITapGestureRecognizer*)gesture
{
UIView *tappedView = [gesture.view hitTest:[gesture locationInView:gesture.view]
withEvent:nil];
NSString *image = [NSString stringWithFormat:@"%li.png",tappedView.tag+1];
UIImageView *anImageView = [[UIImageView
alloc]initWithFrame:CGRectMake((self.view.frame.size.width/2)-150,
(self.view.frame.size.height/2)-206, 300, 412)];
UITapGestureRecognizer *remove = [[UITapGestureRecognizer alloc]initWithTarget:self
action:@selector(getRid:)];
[anImageView addGestureRecognizer:remove];
anImageView.tag = 999;
anImageView.userInteractionEnabled = YES;
anImageView.image = [UIImage imageNamed:image];
[self.view addSubview:anImageView];
}
- (void)getRid:(UITapGestureRecognizer*)tap
{
UIView *v = [self.view viewWithTag:999];
v.hidden = YES;
[v removeFromSuperview];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier = @"Cell";
NSUInteger row = [indexPath row];
UICollectionViewCell *cell = [collectionView
dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
UIImageView *preView = (UIImageView *)[cell viewWithTag:100];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self
action:@selector(createScreen:)];
preView.image = [UIImage imageNamed:[list objectAtIndex:indexPath.row]];
preView.tag = row;
[preView addGestureRecognizer:tap];
return cell;
}
@end
Upvotes: 0
Views: 342
Reputation: 1183
I imagine the problem you are having is that once an image gets set and is reutilized it doesn't get reset. The lines:
UIImageView *preView = (UIImageView *)[cell viewWithTag:100];
//Set Image and tapRecognizer
preView.tag = row;
pretty much guarantee that. You are selecting the image view through its tag and then reassigning that tag to something else. When the cell gets reutilized the tag will no longer be 100
. So
UIImageView *preView = (UIImageView *)[cell viewWithTag:100];
will give you a nil view and nothing will happen.
Try setting an outlet for preView
instead and setting it through the outlet.
Upvotes: 1