UICollectionView无法正常工作

时间:2014-03-08 23:26:32

标签: ios uicollectionview

UICollectionView是否有问题?我正在看几篇关于他们没有重复使用细胞的帖子。我的项目首先只填充前15个,然后当你向后滚动它们都是为了锅?请帮助以下代码:

#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

1 个答案:

答案 0 :(得分:1)

我想你遇到的问题是,一旦图像被设置并被重用,它就不会被重置。这些行:

UIImageView *preView = (UIImageView *)[cell viewWithTag:100];
//Set Image and tapRecognizer
preView.tag = row;

几乎可以保证。您正在通过其标记选择图像视图,然后将该标记重新分配给其他标记。当单元格被重用时,标签将不再是100。所以

UIImageView *preView = (UIImageView *)[cell viewWithTag:100];

会给你一个零视图,什么都不会发生。

尝试设置preView的插座,然后通过插座进行设置。