草庐IT

ios - UICollectionView 的可重用性问题

coder 2024-01-16 原文

我曾使用过 UITableView,但我从未在我的应用程序中使用过 UICollectionView。所以我想以编程方式创建 UICollectionView

以下是我的代码:

UICollectionViewFlowLayout *layout =[[UICollectionViewFlowLayout alloc] init];
    _collectionView=[[UICollectionView alloc] initWithFrame:CGRectMake(0, 43, self.view.frame.size.width, self.view.frame.size.height - 84) collectionViewLayout:layout];
    [_collectionView setDataSource:self];
    [_collectionView setDelegate:self];
    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"];
    layout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    layout.minimumInteritemSpacing = 5;
    [_collectionView setBackgroundColor:self.view.backgroundColor];        
    [self.view addSubview:_collectionView];

委托(delegate)和数据源方法。

#pragma mark -
#pragma mark - UITableView Delegate Methods

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 15;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];

    if (cell.selected)
        cell.backgroundColor = [UIColor lightGrayColor]; // highlight selection cell
    else
        cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background-grid.png"]]; // Default Cell

    UIImageView *imgPhoto = [[UIImageView alloc] init];
    imgPhoto.userInteractionEnabled = YES;
    imgPhoto.backgroundColor = [UIColor grayColor];
    imgPhoto.frame =  CGRectMake(3.5, 5, 90, 80);
    imgPhoto.clipsToBounds = YES;
    imgPhoto.image = [UIImage imageNamed:@"product.png"];
    [cell.contentView addSubview:imgPhoto];

    UILabel *lblCategoryTitle = [[UILabel alloc] init];
    [lblCategoryTitle  setFont: [UIFont fontWithName:@"OpenSans-Bold" size:14]];
    lblCategoryTitle.textAlignment = NSTextAlignmentCenter;
    lblCategoryTitle.frame = CGRectMake(3.5, 90, 90, 24);
    lblCategoryTitle.textColor = [UIColor blackColor];
    lblCategoryTitle.text = @"Product 1"; 
    lblCategoryTitle.backgroundColor = [UIColor clearColor];
    lblCategoryTitle.numberOfLines = 2;
    [cell.contentView addSubview:lblCategoryTitle];

    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(97, 118);
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath  {

    UICollectionViewCell *datasetCell =[collectionView cellForItemAtIndexPath:indexPath];
    datasetCell.backgroundColor = [UIColor lightGrayColor]; // highlight selection
}

-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {

    UICollectionViewCell *datasetCell =[collectionView cellForItemAtIndexPath:indexPath];
    datasetCell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background-grid.png"]]; // default cell
}

然后我的屏幕看起来像

问题 1 -看上面的屏幕,您会看到第一个和第三个项目看起来很模糊(参见产品 1)然后是第二个/中间项目?为什么会这样?

每当我向上/向下滚动 UICollectionView 项目就会被覆盖,看下一张图片

看过这张图片后,根据我对 UITableView 的经验,它的发生是因为 UICollectionView 的单元格的可重用性。

问题2 -那我该如何解决呢?

请给我你的建议并帮助我解决这个问题。

已编辑: (@Dima 的建议)

自定义单元格

.h文件

#import <UIKit/UIKit.h>

@interface customeGridCell : UICollectionViewCell

@property (nonatomic, strong) UIImageView *imgPhoto;
@property (nonatomic, strong) UILabel *lblCategoryTitle;

@end

.m文件

#import "customeGridCell.h"

@implementation customeGridCell

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.imgPhoto = [[UIImageView alloc] init];
        self.imgPhoto.userInteractionEnabled = YES;
        self.imgPhoto.backgroundColor = [UIColor grayColor];
        self.imgPhoto.frame =  CGRectMake(3.5, 5, 90, 80);
        [self addSubview:self.imgPhoto];

        self.lblCategoryTitle = [[UILabel alloc] init];
        [self.lblCategoryTitle  setFont: [UIFont fontWithName:@"OpenSans-Bold" size:14]];
        self.lblCategoryTitle.textAlignment = NSTextAlignmentCenter;
        self.lblCategoryTitle.frame = CGRectMake(3.5, 90, 90, 24);
        self.lblCategoryTitle.textColor = [UIColor blackColor];
        self.lblCategoryTitle.backgroundColor = [UIColor clearColor];
        self.lblCategoryTitle.numberOfLines = 2;
        [self addSubview:self.lblCategoryTitle];
    }
    return self;
}

以及cellForItemAtIndexPath的代码

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    customeGridCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];

    if (cell.selected)
        cell.backgroundColor = [UIColor lightGrayColor]; // highlight selection cell
    else
        cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background-grid.png"]]; // Default Cell


    cell.imgPhoto.image =  [UIImage imageNamed:@"product.png"];
    cell.lblCategoryTitle.text = @"Product 1";

    return cell;
}

最佳答案

问题出在您的 collectionView:cellForItemAtIndexPath: 方法中。每次重复使用单元格时,您都会在彼此之上添加这些 subview 。

您应该创建一个 UICollectionViewCell 子类,并将您想要的所有额外 subview 添加到其初始化程序中。这将确保它们只被添加一次。

示例代码:

这是一个示例,说明如何将 UICollectionViewCell 子类化

@interface MyCustomCell : UICollectionViewCell

@property (nonatomic, strong) UILabel *customLabel;
@property (nonatomic, strong) UIImageView *customImageView;
@end


// in implementation file
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) 
    {
        // initialize label and imageview here, then add them as subviews to the content view
    }
    return self;
}

然后当你抓取一个单元格时,你只需执行如下操作:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MyCustomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];

    if (cell.selected)
        cell.backgroundColor = [UIColor lightGrayColor]; // highlight selection cell
    else
        cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background-grid.png"]]; // Default Cell

    cell.customImageView.image = // whatever
    cell.customLabel.text = // whatever

    return cell;
}

关于ios - UICollectionView 的可重用性问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22678841/

有关ios - UICollectionView 的可重用性问题的更多相关文章

  1. ruby - 在 64 位 Snow Leopard 上使用 rvm、postgres 9.0、ruby 1.9.2-p136 安装 pg gem 时出现问题 - 2

    我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po

  2. ruby - 通过 rvm 升级 ruby​​gems 的问题 - 2

    尝试通过RVM将RubyGems升级到版本1.8.10并出现此错误:$rvmrubygemslatestRemovingoldRubygemsfiles...Installingrubygems-1.8.10forruby-1.9.2-p180...ERROR:Errorrunning'GEM_PATH="/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/ruby-1.9.2-p180@global:/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/rub

  3. ruby - 通过 RVM (OSX Mountain Lion) 安装 Ruby 2.0.0-p247 时遇到问题 - 2

    我的最终目标是安装当前版本的RubyonRails。我在OSXMountainLion上运行。到目前为止,这是我的过程:已安装的RVM$\curl-Lhttps://get.rvm.io|bash-sstable检查已知(我假设已批准)安装$rvmlistknown我看到当前的稳定版本可用[ruby-]2.0.0[-p247]输入命令安装$rvminstall2.0.0-p247注意:我也试过这些安装命令$rvminstallruby-2.0.0-p247$rvminstallruby=2.0.0-p247我很快就无处可去了。结果:$rvminstall2.0.0-p247Search

  4. ruby - Fast-stemmer 安装问题 - 2

    由于fast-stemmer的问题,我很难安装我想要的任何ruby​​gem。我把我得到的错误放在下面。Buildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingfast-stemmer:ERROR:Failedtobuildgemnativeextension./System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/rubyextconf.rbcreatingMakefilemake"DESTDIR="cleanmake"DESTDIR=

  5. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  6. ruby - 安装 Ruby 时遇到问题(无法下载资源 "readline--patch") - 2

    当我尝试安装Ruby时遇到此错误。我试过查看this和this但无济于事➜~brewinstallrubyWarning:YouareusingOSX10.12.Wedonotprovidesupportforthispre-releaseversion.Youmayencounterbuildfailuresorotherbreakages.Pleasecreatepull-requestsinsteadoffilingissues.==>Installingdependenciesforruby:readline,libyaml,makedepend==>Installingrub

  7. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  8. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  9. ruby-on-rails - 简单的 Ruby on Rails 问题——如何将评论附加到用户和文章? - 2

    我意识到这可能是一个非常基本的问题,但我现在已经花了几天时间回过头来解决这个问题,但出于某种原因,Google就是没有帮助我。(我认为部分问题在于我是一个初学者,我不知道该问什么......)我也看过O'Reilly的RubyCookbook和RailsAPI,但我仍然停留在这个问题上.我找到了一些关于多态关系的信息,但它似乎不是我需要的(尽管如果我错了请告诉我)。我正在尝试调整MichaelHartl'stutorial创建一个包含用户、文章和评论的博客应用程序(不使用脚手架)。我希望评论既属于用户又属于文章。我的主要问题是:我不知道如何将当前文章的ID放入评论Controller。

  10. 【高数】用拉格朗日中值定理解决极限问题 - 2

    首先回顾一下拉格朗日定理的内容:函数f(x)是在闭区间[a,b]上连续、开区间(a,b)上可导的函数,那么至少存在一个,使得:通过这个表达式我们可以知道,f(x)是函数的主体,a和b可以看作是主体函数f(x)中所取的两个值。那么可以有,  也就意味着我们可以用来替换 这种替换可以用在求某些多项式差的极限中。方法: 外层函数f(x)是一致的,并且h(x)和g(x)是等价无穷小。此时,利用拉格朗日定理,将原式替换为 ,再进行求解,往往会省去复合函数求极限的很多麻烦。使用要注意:1.要先找到主体函数f(x),即外层函数必须相同。2.f(x)找到后,复合部分是等价无穷小。3.要满足作差的形式。如果是加

随机推荐