UICollectionView中重用的单元格显示多个UIImageViews时,它们应该只显示一个

时间:2013-10-09 10:18:38

标签: ios objective-c uiimage uicollectionview

我的UICollectionView出了问题。最初它显示正常,显示一个单元格网格,每个单元格都有一个UIImageView。这些UIImageViews显示的PNG具有透明度,存储在应用的捆绑包中。

我的问题是,一旦滚动UICollectionView,某些单元格似乎已损坏。

损坏的单元格显示多个图像堆叠在一起,最顶层的图像是它应该显示的图像,下面的图像是应该在其他单元格中使用的图像。

我最好的猜测是,这与UICollectionView中的单元格重用方式有关,但我愿意接受建议。

这是我用于在UICollectionView

中创建单元格的委托代码
// creates the individual cells to go in the menu view
- (UICollectionViewCell*) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    // create collection view cell
    UICollectionViewCell * cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];

    // create a uiview where we can place all views that need to go into this cell
    UIView * contents=[[UIView alloc] initWithFrame:cell.contentView.bounds];
    [contents setBackgroundColor:[UIColor clearColor]];
    [cell.contentView addSubview:contents];

    // add a button image
    NSString * buttonPath=[[NSBundle mainBundle] pathForResource:@"button" ofType:@"png" inDirectory:[[buttons objectAtIndex:indexPath.row] objectForKey:@"name"]];
    UIImage * button=[UIImage imageWithContentsOfFile:buttonPath];
    UIImageView * buttonView=[[UIImageView alloc] initWithImage:button];
    [buttonView setContentMode:UIViewContentModeScaleAspectFit];
    [buttonView setFrame:contents.bounds];
    [contents addSubview:buttonView];

    // set tag to the indexPath.row so we can access it later
    [cell setTag:indexPath.row];

    // add interactivity
    UITapGestureRecognizer * tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onButtonTapped:)];
    [tap setNumberOfTapsRequired:1];
    [cell addGestureRecognizer:tap];

    // return the cell
    return cell;

}

如果需要,我可以提供更多代码。

如何阻止细胞腐败?

7 个答案:

答案 0 :(得分:42)

问题在于,您不断向UICollectionViewCell添加视图,因为UICollectionView会自动重复使用这些视图。因此,当UIImageView被调用时,旧的cellForItemAtIndexPath:仍然在单元格上,因为你要再添加一个{。}}。

请勿使用addSubview:

相反,您可以制作一个自定义单元格,其中包含您想要的所有视图。因此,当调用cellForItemAtIndexPath:时,您只需要设置此CustomCollectionViewCell的内容。

这样一定会不会被破坏。


如何构建CustomCell。

Step1 :创建.h& .m class。

CustomCell.h

#import <UIKit/UIKit.h>

@interface CustomCell : UICollectionViewCell
{
    UIImageView *imageView;
}

@property (nonatomic, retain) UIImageView *imageView; //this imageview is the only thing we need right now.

@end

CustomCell.m

#import "CustomCell.h"

@implementation CustomCell

@synthesize imageView;

- (id)initWithFrame:(CGRect)aRect
{
    if (self = [super initWithFrame:aRect])
    {
         //we create the UIImageView in this overwritten init so that we always have it at hand.
         imageView = [UIImageView alloc] init];
         //set specs and special wants for the imageView here.
         [self addSubview:imageView]; //the only place we want to do this addSubview: is here!

         //You wanted the imageView to react to touches and gestures. We can do that here too.
         UITapGestureRecognizer * tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onButtonTapped:)];
        [tap setNumberOfTapsRequired:1];
        [self addGestureRecognizer:tap];


        //We can also prepare views with additional contents here!
        //just add more labels/views/whatever you want.
    }
    return self;
}

-(void)onButtonTapped:(id)sender
{
    //the response to the gesture.
    //mind that this is done in the cell. If you don't want things to happen from this cell.
    //then you can still activate this the way you did in your question.

}

Step2 :导入它! 现在我们创建了CustomCell,我们可以在我们想要使用它的类中导入它。

第3步:在行动中使用它!

// creates the individual cells to go in the menu view
- (CustomCell*) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    // create collection view cell
    CustomCell *cell = (CustomCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"CustomCell" forIndexPath:indexPath]; //this is the place where the CustomCell does his magic.
    //Make sure to use the CustomCellReuseId that you register in the viewdidload/loadview (step4)

    // add a button image
    NSString * buttonPath=[[NSBundle mainBundle] pathForResource:@"button" ofType:@"png" inDirectory:[[buttons objectAtIndex:indexPath.row] objectForKey:@"name"]];

    cell.imageView.image = [UIImage imageWithContentsOfFile:buttonPath]; //place the image on the CustemCell.imageView as we prepared.

    // set tag to the indexPath.row so we can access it later
    [cell setTag:indexPath.row]; //we don't need this to access the cell but I left this in for your personal want.

/*
 * we can now do this from the CustomCell as well!
 *
    // add interactivity
    UITapGestureRecognizer * tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onButtonTapped:)];
    [tap setNumberOfTapsRequired:1];
    [cell addGestureRecognizer:tap];
*/
    // return the cell
    return cell;

}

Step4 :将单元格注册到collectionView

在viewDidLoad / loadView中添加以下行:

[_collectionView registerClass:[CustomCell class] forCellWithReuseIdentifier:@"CustomCell"];

Step5 :享受吧! 您的CustomCell已完成。现在做任何你喜欢的事情,也不要忘记喝点咖啡。

答案 1 :(得分:6)

之后
UICollectionViewCell * cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];

只需添加此行

即可
[[[cell contentView] subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];

答案 2 :(得分:4)

发生这种情况,因为每次向您的单元格添加UIImageView以解决此问题时,您必须创建一个自定义单元格,然后像使用它一样使用它:

<强> Custom.h

#import <UIKit/UIKit.h>

@interface CustomCell : UICollectionViewCell

@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@end

<强> Custom.m

#import "CustomCell.h"

@implementation CustomCell

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end

您的控制器

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

    CustomCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"CustomCell" forIndexPath:indexPath];

    NSString * buttonPath=[[NSBundle mainBundle] pathForResource:@"button" ofType:@"png" inDirectory:[[buttons objectAtIndex:indexPath.row] objectForKey:@"name"]];
    UIImage * button=[UIImage imageWithContentsOfFile:buttonPath];

    [cell.imageView setImage:button];

    return cell;
}

您还必须将标识符之类的“CustomCell”设置为IB中的单元格

答案 3 :(得分:2)

对于那些正在寻找Swifty答案的人,请将此功能添加到CustomCell课程中:

override func prepareForReuse() {
    contentView.subviews.forEach({ $0.removeFromSuperview() })
    // replace contentView with the superview of the repeating content.
}

答案 4 :(得分:0)

对于以编程方式添加UICollectionView并拥有自定义单元格的任何人,换句话说没有XIB文件,那么您必须将此行添加到viewDidLoad

[_collectionView registerClass:[CustomCell class] forCellWithReuseIdentifier:@"cellIdentifier"];

答案 5 :(得分:0)

This is for removing duplicate text from label in uicollectionviewcell.
   // Viewdidload
   [_collectionView registerClass:[UICollectionviewcell class]     forCellWithReuseIdentifier:@"cellIdentifier"];
   //in this method create label like this
   -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
  {
     UICollectionViewCell *cell=[collectionView   dequeueReusableCellWithReuseIdentifier:@"cellidentifier" forIndexPath:indexPath];
   for (UILabel *lbl in cell.contentView.subviews)
        {
            if ([lbl isKindOfClass:[UILabel class]])
            {
                [lbl removeFromSuperview];
            }
        }
UILabel *nameLbl=[[UILabel alloc] initWithFrame:CGRectMake(0, 10, 50, 20)];
   nameLbl.text=[Array objectAtIndex:indexpath.row];                                                                                                                                  
        nameLbl.textColor=[UIColor whiteColor];
        [cell.contentView addSubview:nameLbl];
return cell;

   }

答案 6 :(得分:-1)

for (UIView *prevSubview in cell.contentView.subviews) {
    [prevSubview removeFromSuperview];
}